From 9f581f9321c2926f2968e7078973bee5a7129067 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:42:13 +1300 Subject: [PATCH 01/29] Implement genuine Game Design realm policy source and publication proof --- .../game-design-service/api-contracts.md | 31 + .../game-design-service/version-control.md | 4 + ...ame-authoring-publishing-and-activation.md | 4 + services/game-design-service/build.gradle.kts | 15 + ...almPolicyPublicationReadConfiguration.java | 29 + .../draft/AuthoredDraftPublishSelection.java | 146 ++ ...thoredDraftPublishSelectionRepository.java | 272 +++ .../DraftCommitCoordinatorRepository.java | 1679 +++++++++++++++++ .../GameDesignDraftTerminalOperation.java | 86 + .../draft/GameDesignDraftTerminalOutcome.java | 177 ++ ...eDesignDraftTerminalOutcomeRepository.java | 637 +++++++ .../draft/GameDesignReviewedBaseEvidence.java | 145 ++ .../GameDesignReviewedBaseRepository.java | 208 ++ .../dto/PublishParticipantDigestDto.java | 23 + .../dto/PublishedReleaseBundleDto.java | 78 +- .../gamedesign/entity/LaunchDescriptor.java | 16 + .../gamedesign/entity/PublishAttempt.java | 1 + .../entity/PublishedReleaseBundle.java | 7 + .../firemud/gamedesign/entity/Version.java | 6 + .../entity/VersionAssetArtifact.java | 4 + .../publication/CommandApplication.java | 97 + .../publication/CommandSnapshot.java | 134 ++ .../gamedesign/publication/CommandSource.java | 645 +++++++ .../publication/CommandSourceRepository.java | 809 ++++++++ .../GameDesignPublicationOperation.java | 42 + ...eDesignPublicationOperationRepository.java | 254 +++ ...GameDesignPublicationOperationService.java | 70 + ...ignPublicationTerminalReadGrpcService.java | 110 ++ .../GameDesignSourceRepository.java | 322 ++++ .../PublicationReleaseContent.java | 65 + .../publication/RealmPolicyApplication.java | 96 + .../publication/RealmPolicyGenesis.java | 48 + .../RealmPolicyPublicationGrpcService.java | 195 ++ .../RealmPolicyPublicationRepository.java | 565 ++++++ .../RealmPolicyPublicationService.java | 73 + .../RealmPolicyPublishedEvidence.java | 221 +++ .../RealmPolicyPublishedEvidenceMapper.java | 45 + .../publication/RealmPolicySnapshot.java | 81 + .../publication/RealmPolicySource.java | 192 ++ .../RealmPolicySourceRepository.java | 607 ++++++ .../publication/RealmPolicySourceService.java | 53 + .../repository/GameAssetRepository.java | 5 +- .../gamedesign/repository/GameRepository.java | 22 +- .../LaunchDescriptorRepository.java | 173 +- .../repository/PublishAttemptRepository.java | 121 +- .../PublishedReleaseBundleRepository.java | 332 +++- .../VersionAssetArtifactRepository.java | 68 +- .../VersionAssetPublicationRepository.java | 570 ++++++ .../repository/VersionRepository.java | 210 ++- .../service/ExportedAssetManifest.java | 37 +- .../service/PublishedArtifactDigest.java | 62 + .../PublishedReleaseBundleService.java | 11 + .../service/VersionAssetArtifactService.java | 10 + .../VersionAssetExportCandidateService.java | 9 + .../VersionAssetPublicationService.java | 18 + .../impl/PublishedReleaseBundleContract.java | 122 ++ .../impl/VersionAssetArtifactServiceImpl.java | 165 +- ...ersionAssetExportCandidateServiceImpl.java | 478 +++++ .../VersionAssetPublicationServiceImpl.java | 118 ++ .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 5 + .../V35.1__canonical_version_identity.sql | 116 ++ ....2__canonical_release_version_identity.sql | 86 + ...hored_source_launch_descriptor_binding.sql | 147 ++ ...que_published_release_bundle_reference.sql | 56 + .../V37__version_asset_export_snapshot.sql | 348 ++++ .../V38__published_asset_digest_evidence.sql | 75 + ...V39__publication_evidence_text_storage.sql | 11 + ...V42__durable_draft_commit_coordination.sql | 865 +++++++++ .../V43__authored_draft_publish_selection.sql | 265 +++ ...uthored_draft_publish_request_identity.sql | 5 + ...lected_publish_attempt_digest_capacity.sql | 5 + ...8__game_design_draft_terminal_outcomes.sql | 405 ++++ ...ublished_world_start_location_evidence.sql | 238 +++ ...0__publication_operation_terminal_seal.sql | 180 ++ ...publication_terminal_content_and_epoch.sql | 141 ++ .../V52__immutable_realm_policy_source.sql | 311 +++ ...aled_realm_policy_publication_evidence.sql | 278 +++ .../V54__immutable_command_source.sql | 480 +++++ .../V55__immutable_reviewed_draft_base.sql | 171 ++ .../draft/IsolatedPublicationOwnerSetup.java | 307 +++ .../IsolatedPublicationOperationFixtures.java | 173 ++ .../impl/PublishedWorldSelectorFixtures.java | 475 +++++ ...meDesignSourcePostgresIntegrationTest.java | 408 ++++ ...lmPolicySourcePostgresIntegrationTest.java | 737 ++++++++ ...ationOperationPostgresIntegrationTest.java | 1254 ++++++++++++ ...icyPublicationPostgresIntegrationTest.java | 778 ++++++++ ...olicyPublicationReadConfigurationTest.java | 97 + .../AuthoredDraftPublishSelectionTest.java | 213 +++ .../GameDesignReviewedBaseEvidenceTest.java | 61 + .../publication/CommandSourceTest.java | 261 +++ .../RealmPolicyApplicationTest.java | 97 + ...RealmPolicyPublicationGrpcServiceTest.java | 420 +++++ .../RealmPolicyPublicationMtlsTest.java | 345 ++++ .../RealmPolicyPublishedEvidenceTest.java | 227 +++ .../publication/RealmPolicySourceTest.java | 122 ++ .../LaunchDescriptorRepositoryTest.java | 73 + .../PublishedReleaseBundleRepositoryTest.java | 291 +++ .../VersionAssetArtifactRepositoryTest.java | 30 + .../repository/VersionRepositoryTest.java | 14 + .../VersionAssetArtifactServiceImplTest.java | 227 ++- 101 files changed, 21453 insertions(+), 170 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V55__immutable_reviewed_draft_base.sql create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe3ee5265f..2d43e4a5bd 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -82,10 +82,14 @@ When Temporal is disabled or its beans are absent, `PublishVersion` uses the sam The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). +The published realm-policy owner read is present behind the default-off `firemud.game-design.published-realm-entry-policy-read.enabled` provider. This slice adds only the two `PublishedRealmEntryPolicyService` methods to the base and production bearer-exemption lists; each handler still requires the verified same-namespace Game Session mTLS identity before decoding or owner access. Source and focused test fixtures are present, but final A-dependent compilation, physical PostgreSQL execution, and runtime consumer/activation proof remain unestablished. + ## gRPC APIs - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. +- `ResolvePublishedRealmEntryPolicy` – returns immutable Game Design policy and provenance for one exact canonical tenant/version and world/realm selector pair; it does not compose runtime catalog or admission state. +- `ListPublishedRealmEntryPolicies` – returns the complete bounded policy set and owner-bound count/digest for one exact canonical tenant/version; it does not activate runtime state. - `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -114,6 +118,30 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e These gRPC entries are the discoverability index for the control-plane contracts described in [Game Templates and Configuration Tools](game-templates.md) and related architecture docs. When request/response schemas evolve, the proto contract and those architecture sections must be updated in the same change so launch-resolution and template-phase semantics do not drift. +### Authored source genesis and deterministic replay + +Game Design records an explicit immutable empty genesis only as part of genuinely new Draft creation. A missing source row is never evidence of empty content. Retained Drafts require a separate audited, authoritative baseline bound to their exact owner target and retained content; unknown or contradictory legacy lineage remains denied. Genesis and retained enrollment are owner evidence, not caller declarations, and neither substitutes for the creator authorization or exact affected-owner fencing required by [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). + +The closed `game-design-draft-base-reference/v1` grammar admits exactly two forms in the immutable reviewed proposal's `baseCommitId`: `genesis:` for the genuinely new Draft's first authored base, or the exact canonical UUID of a retained authored commit. UUIDs are non-nil lower-case canonical text; other prefixes, opaque labels, missing values and ambiguous references deny. The genesis form names the separately persisted shared command/policy receipt, not an authored commit. It never populates actual `commitId`, `sourceCommitId` or `inheritedCommitId` UUID fields. + +Before accepting the reviewed proposal, Game Design resolves that exact reference against its own persisted canonical target and Draft. Genesis resolution proves the original shared receipt UUID, creation lineage, receipt kind and version, complete stored policy/command evidence and evidence digest. Authored-base resolution proves the exact retained synchronized commit, complete owner result and source evidence for that target. The complete resolved evidence and digest are frozen with the exact reviewed binding, base, complete diff and affected epochs; retry preserves them byte-for-byte. Wrong-Draft, unknown, mismatched or contradictory receipt, digest or retained commit fails before a new application. Retained Drafts do not acquire inferred empty genesis. A later synchronized change confined to disjoint scopes does not rewrite the reviewed base or itself create a conflict; freshness remains the complete affected-owner epoch check in ADR 0129, not equality with the latest visible commit. + +Effective command and policy source is reconstructed deterministically from that proved baseline and the canonical commit/revision order. Each typed upsert or explicit deletion names its stable authored key and preserves the original immutable base, complete diff, revision identity, input digest and affected scope epochs. An omitted row is not a deletion. Partial owner applications remain invisible; only the exact fully synchronized owner fence advances the effective snapshot. Publication freezes the complete effective selected snapshot under the same owner serialization boundary, rather than selecting mutable latest rows or treating the last commit's diff as the full source. Exact retry and readback preserve the original source and capture bytes. No source enrollment or capture grants publication, launch or gameplay authority. + +### Published realm-entry policy owner read + +Game Design owns typed `REALM_ENTRY_POLICY` source and immutable published policy evidence. The policy data is one closed v1 JSON object with exactly `schemaVersion`, `worldSlug`, `worldDisplayName`, `realmSlug`, `realmDisplayName`, `visible`, `publicProduction`, `stateScope`, and `entryPolicy`. The schema version is integer `1`; all fields are required and typed, without boolean defaults. Slugs are canonical lower-case ASCII selectors of at most 64 characters; display names are trimmed, control-free text of at most 128 Unicode code points. The UTF-8 policy document is bounded to 4096 bytes. Unknown or duplicate JSON fields, malformed values, and unsupported policies deny. V1 supports only `entryPolicy=PRESEEDED_ONLY` with `stateScope=SHARED|ISOLATED`; descriptor and template fields do not belong to this policy. + +The [durable Draft coordinator](./version-control.md#design-time-synchronization) owns application and visibility. Source changes bind the complete canonical target, original authored revision and logical identity, exact input/commit digest, and affected policy scope epoch. A selected commit's diff is not the complete effective policy set: Game Design retains the complete synchronized effective snapshot, including unchanged policy provenance inherited from earlier owner applications. Partial owner writes remain invisible. A missing or contradictory owner baseline is denied, not reconstructed from the latest mutable revision, missing rows, slugs or numeric equality. Retained history never acquires inferred source authority. + +Publication freezes that exact selected synchronized source and the complete original publication operation once. Source mutation and freeze share the owning Version serialization boundary. The effective published set has at most 128 policies, unique `(worldSlug, realmSlug)` selectors, tenant/version-wide `realmSlug` uniqueness, and exactly one `visible=true && publicProduction=true` policy. Game Design persists separate immutable policy rows and allocates each policy UUID once. Exact retry returns the original identities and bytes; conflicting evidence cannot silently select another source or bundle. Policy evidence binds canonical tenant/version and owner provenance, original source commit/revision/logical identity, the selected source capture, and the genuine sealed publication's workflow, manifest and release-content identity/digest. A source capture alone is not `PUBLISHED`. These separate rows and digests do not rewrite the closed release, terminal, launch-descriptor or release-attestation bytes. + +`ResolvePublishedRealmEntryPolicy` proves one exact selector; `ListPublishedRealmEntryPolicies` proves the complete ordered set, exact count and set digest. Both authenticate the same-namespace Game Session workload before decoding or owner access, independently read the exact canonical owner target and its full Version in `PUBLISHED` or `ACTIVE`, and verify the frozen source against the actual sealed publication and immutable release. Missing, contradictory, wrong-operation or mismatched digest evidence denies the complete response. No policy is inferred from a bundle, current mutable revisions or a caller's publication claim. The set read is complete-or-error: a bounded read detects an oversized set instead of returning a truncated prefix, and individual-selector proof cannot substitute for complete-set cardinality. Private owner row keys remain provenance, not public tenant/version identity. + +The [published-policy read proto](../../../../protos/game-design/v1/published_realm_entry_policy_service.proto) owns the closed schema-1 wire shape. Each read binds the configured namespace, a distinct non-nil canonical read-request UUID and canonical tenant/Version UUIDs; Resolve additionally binds the exact world and realm selectors. The response echoes that complete read request and carries the complete canonical `game-design-published-realm-policy-evidence/v1` set, not a selector-only fragment. This separate carrier retains the original operation, captured selected source and PUBLISHED terminal bytes, actual immutable release reference/content digest, workflow, manifest and original publication epoch, together with the ordered policy identities, source provenance, count and policy/set digests. It does not extend the closed release or terminal representation. Receivers authenticate Game Design, reject unknown fields, unsupported schemas or changed echoes, and verify every original evidence binding and digest before consuming content; digest integrity alone is not workload authentication. + +Published policy evidence alone establishes no runtime catalog, realm UUID, pointer, namespace resolution, lifecycle readiness, Entity assignment or admission. Game Session remains the runtime catalog owner and must compose the policy with its other owner evidence. Missing policy evidence denies that intake without enabling a fallback; [implementation status and proof](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) remain separate from this target contract. + ## REST & gRPC Endpoints Default ports: REST on `8080`, gRPC on `6565`. @@ -168,6 +196,9 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetVersionAssetPurgeStatus(GetVersionAssetPurgeStatusRequest) returns (GetVersionAssetPurgeStatusResponse)` – live operator-visible read of in-flight or failed purge workflow status; the target operation-ledger replay and reconciliation boundary remains incomplete. - `RepairPublishedVersionAssets(RepairPublishedVersionAssetsRequest) returns (RepairPublishedVersionAssetsResponse)` – live exact-bytes repair endpoint; target durable snapshot/readback and pre-write attestation proof are not implemented, and current repair can write version-prefix objects before mismatch detection. +- `ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) returns (ResolvePublishedRealmEntryPolicyResponse)` – returns immutable Game Design policy and provenance evidence for the exact canonical tenant UUID, published version, and world/realm selector pair. It requires the exact `PUBLISHED` or `ACTIVE` full version and release bundle; a missing policy never falls back to legacy bundle or mutable revision data. +- `ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) returns (ListPublishedRealmEntryPoliciesResponse)` – returns the complete bounded frozen policy set and owner-bound count/digest for one canonical tenant UUID and exact published version; no pagination, truncation, legacy fallback, or partial success. + #### `AppendPluginVersionSignatureEvidence` (target only) This target mutation belongs to Game Design and is separate from runtime plugin activation. It is a signed-intake-only supplement to `UploadPluginBundle`: the target row must have entered the lifecycle through the allowlisted Ed25519 signed-intake path, and an unsigned package cannot use this RPC to manufacture signature evidence. Unsigned operator-permitted intake, when implemented under ADR 0111, needs its own platform-acceptance/approval evidence path and is not represented by this signature ledger. For signed intake, the mutation appends to an immutable evidence ledger; it never rewrites the uploaded bundle, signed payload, `pluginVersionId`, `bundleDigest`, publication status, or publication content. It is allowed only while the design-time status is `SIGNATURE_VERIFIED` or `PUBLISHED`; other statuses fail deterministically without mutation. A successful append on a `PUBLISHED` version does not republish or change its status, and an append on `SIGNATURE_VERIFIED` leaves that status unchanged. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 921444e405..33fe426dde 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -58,6 +58,10 @@ Game Design owns the durable, creator-visible coordination record for every shar - Game Design advances the synchronized fence only after every required owner durably reports the same exact commit and digest. Partial application remains diagnostic workflow state and cannot satisfy `IN_SYNC` or become a publish target. - Conflict assistance may construct a new proposed diff, but it must produce a new digest and exact base/epoch binding for creator review. Reconciliation never silently merges a stale proposal. +The [authored-source genesis and replay contract](./api-contracts.md#authored-source-genesis-and-deterministic-replay) requires explicit new-Draft genesis or an audited retained baseline before synchronized effective source can be captured. Its closed first-proposal base reference names the independently persisted genesis receipt, not a fabricated authored commit; subsequent authored bases name exact retained commit UUIDs. Proposal acceptance and frozen selection preserve the complete owner-resolved base evidence and digest rather than an opaque caller label. History and release assembly retain its stable-key replay and original source provenance; absent or unknown lineage cannot be normalized into empty content. + +Game Design's [realm-entry policy owner contract](./api-contracts.md#published-realm-entry-policy-owner-read) separately freezes the complete effective policy source at that selected synchronized fence. A latest mutable revision query or the selected commit's diff alone cannot supply unchanged inherited policy state. Policy capture and immutable published-policy association preserve the original operation and genuine terminal bundle without adding policy fields to the existing closed release or terminal representation; they do not establish runtime catalog or admission authority. + #### Publication freeze and owner handoff (Target State) The synchronized Draft fence is also the lifecycle handoff into publication. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index df5cae8a26..f373c4f018 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -12,6 +12,10 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. +### Immutable command and realm-policy source + +Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The focused source and PostgreSQL test fixtures are present; post-A compilation, focused execution, physical PostgreSQL proof, and runtime-consumer composition remain pending. The read provider remains nonactivating, and its fixtures do not establish production Account or World authority. + ### Fresh-tenant identity prerequisite The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 264cc3ebfc..f404aca6d2 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -1,3 +1,4 @@ +import org.gradle.api.plugins.jvm.JvmTestSuite apply(from = "${rootDir}/gradle/proto-convention.gradle") @@ -11,7 +12,21 @@ firemudJooq { packageName.set("net.firedevops.firemud.gamedesign.jooq") } +testing { + suites { + named("test") { + sources.java.srcDir("src/sharedTest/java") + } + named("integrationTest") { + sources.java.srcDir("src/sharedTest/java") + } + } +} + dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) + testImplementation(libs.bouncycastle.pkix) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java new file mode 100644 index 0000000000..24e65c58fd --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfiguration.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.gamedesign.config; + +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Explicit opt-in composition for the protected published realm-policy owner read. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-design.published-realm-entry-policy-read", + name = "enabled", + havingValue = "true") +public class RealmPolicyPublicationReadConfiguration { + + @Bean + RealmPolicyPublicationRepository realmPolicyPublicationRepository(DSLContext dsl) { + return new RealmPolicyPublicationRepository(dsl); + } + + @Bean + RealmPolicyPublicationService realmPolicyPublicationService( + RealmPolicyPublicationRepository repository, PlatformTransactionManager transactions) { + return new RealmPolicyPublicationService(repository, transactions); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java new file mode 100644 index 0000000000..94ec38dc56 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; + +/** + * Exact existing synchronized Draft selection. The shared codec preserves the original V43 bytes + * and digest; neither this retained selection nor codec validation establishes publication + * authority. + */ +public final class AuthoredDraftPublishSelection { + private final AuthoredDraftPublishSelectionBinding binding; + + private AuthoredDraftPublishSelection(AuthoredDraftPublishSelectionBinding binding) { + this.binding = Objects.requireNonNull(binding); + } + + public static AuthoredDraftPublishSelection capture( + PublishIntent intent, TargetProof target, PublicationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + var fence = evidence.visibilityFence(); + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.capture( + sharedIntent(intent), + target, + evidence.binding(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + fence.target(), + fence.requestId(), + fence.commitId(), + fence.inputDigest(), + fence.resultVectorJson(), + fence.createdAt()))); + } + + public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.fromStored(storedJson, storedDigest)); + } + + public PublishIntent intent() { + var intent = binding.intent(); + return new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + public TargetProof target() { + return binding.target(); + } + + public DraftCommitBinding selectedCommit() { + return binding.selectedCommit(); + } + + public UUID fenceRequestId() { + return binding.fenceRequestId(); + } + + public UUID fenceCommitId() { + return binding.fenceCommitId(); + } + + public String fenceInputDigest() { + return binding.fenceInputDigest(); + } + + public String fenceResultVectorJson() { + return binding.fenceResultVectorJson(); + } + + public String fenceCreatedAt() { + return binding.fenceCreatedAt(); + } + + public String canonicalJson() { + return binding.canonicalJson(); + } + + public byte[] canonicalBytes() { + return binding.canonicalBytes(); + } + + public String digest() { + return binding.digest(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelection selection + && binding.equals(selection.binding)); + } + + @Override + public int hashCode() { + return binding.hashCode(); + } + + private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent( + PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + return new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + /** Full original eight caller inputs, retaining the existing public API. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + new AuthoredDraftPublishSelectionBinding.PublishIntent( + canonicalTenantId, + canonicalVersionId, + publishRequestId, + expectedVersionStateEpoch, + notes, + selectedCommitRequestId, + selectedCommitId, + selectedCommitDigest); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java new file mode 100644 index 0000000000..31adbd248b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitStateConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.LockedVersion; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Retains the first exact authored-Draft selection for a full-version publication request. The + * durable row is a reservation; this repository does not release it or infer any World freeze or + * terminal participant outcome. Later workflow code must recover the same selection and persist + * only definitive authenticated owner readback in its separately owned boundary. + */ +@Repository +public class AuthoredDraftPublishSelectionRepository { + private static final String SELECTION_TABLE = "game_design_authored_draft_publish_selection"; + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborators only; no resources are acquired and no finalizer is used.") + public AuthoredDraftPublishSelectionRepository( + DSLContext dsl, DraftCommitCoordinatorRepository coordinator) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.coordinator = Objects.requireNonNull(coordinator, "coordinator"); + } + + /** + * Selects exactly one caller-named current synchronized commit for an existing full Draft + * Version. Exact request replay returns the immutable first selection before reading mutable + * Version state or current-fence state again. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public SelectionSnapshot reserve(PublishIntent intent) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(intent, "intent"); + + Optional prior = + readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId()); + if (prior.isPresent()) { + requireExactIntent(intent, prior.get().selection().intent()); + return prior.get(); + } + + LockedVersion version = + coordinator.lockVersionTarget(intent.canonicalTenantId(), intent.canonicalVersionId()); + SelectionSnapshot existing = findByTarget(version.target(), false); + if (existing != null) { + requireExactIntent(intent, existing.selection().intent()); + return existing; + } + + requireEligibleFirstSelection(version, intent); + if (coordinator.readApplicationSlot(version.target()).isPresent()) { + throw new DraftCommitStateConflictException( + "An active or unresolved owner application prevents Draft publication selection"); + } + PublicationEvidence evidence = + coordinator.requireSynchronizedPublicationEvidence( + version.target(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture(intent, version.target(), evidence); + + int inserted; + try { + inserted = insert(selection); + } catch (DataAccessException exception) { + if (isUniqueConstraintViolation(exception)) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publication operation already reserves an exact Version", exception); + } + throw exception; + } + SelectionSnapshot persisted = findByTarget(version.target(), false); + if (persisted == null) { + throw new IllegalStateException( + "Durable authored Draft publication selection disappeared after insert"); + } + requireExactIntent(intent, persisted.selection().intent()); + if (inserted == 0 && !selection.equals(persisted.selection())) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publish request was reused with changed exact binding data"); + } + return persisted; + } + + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional readByPublishRequest( + UUID canonicalTenantId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND publish_request_id = ?", + canonicalTenantId, + publishRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional read( + UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + canonicalTenantId, + canonicalVersionId); + if (row == null || !publishRequestId.equals(row.get("publish_request_id", String.class))) { + return Optional.empty(); + } + return Optional.of(toSnapshot(row)); + } + + private int insert(AuthoredDraftPublishSelection selection) { + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + return dsl.execute( + "INSERT INTO " + + SELECTION_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, publish_request_id, version_state_epoch, " + + "selected_commit_request_id, selected_commit_id, selected_commit_digest, " + + "selection_digest, selection_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selection.digest(), + selection.canonicalJson()); + } + + private SelectionSnapshot findByTarget(TargetProof target, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? null : toSnapshot(row); + } + + private SelectionSnapshot toSnapshot(Record row) { + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.fromStored( + row.get("selection_json", String.class), row.get("selection_digest", String.class)); + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + if (!row.get("canonical_tenant_id", UUID.class).equals(target.canonicalTenantId()) + || !row.get("canonical_version_id", UUID.class).equals(target.canonicalVersionId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(target.gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(target.gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(target.sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class).equals(target.sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class).equals(target.sourceProvenanceKind()) + || !row.get("publish_request_id", String.class).equals(intent.publishRequestId()) + || !Long.toString(row.get("version_state_epoch", Long.class)) + .equals(intent.expectedVersionStateEpoch()) + || !row.get("selected_commit_request_id", UUID.class) + .equals(intent.selectedCommitRequestId()) + || !row.get("selected_commit_id", UUID.class).equals(intent.selectedCommitId()) + || !row.get("selected_commit_digest", String.class).equals(intent.selectedCommitDigest())) { + throw new IllegalStateException( + "Authored Draft publication selection indexed identity differs from exact stored binding"); + } + return new SelectionSnapshot(selection, row.get("created_at", OffsetDateTime.class)); + } + + private static void requireEligibleFirstSelection(LockedVersion version, PublishIntent intent) { + if (!"DRAFT".equals(version.versionState()) + || version.scriptOnly() + || version.scriptPatchVersion() != null + || version.baseVersionId() != null) { + throw new DraftCommitStateConflictException( + "Only an existing non-script-only full Version in DRAFT can be selected for publication"); + } + if (!Long.toString(version.versionStateEpoch()).equals(intent.expectedVersionStateEpoch())) { + throw new DraftCommitStateConflictException( + "Authored Draft publication selection has a stale Version state epoch"); + } + } + + private static void requireExactIntent(PublishIntent expected, PublishIntent actual) { + if (!expected.equals(actual)) { + throw new DraftCommitIdentityConflictException( + "Publish request identity was reused with changed notes, target, epoch, or commit selection"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Authored Draft selection mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + 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 canonical non-nil UUID"); + } + } + + private static boolean isUniqueConstraintViolation(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState())) { + return true; + } + current = current.getCause(); + } + return false; + } + + public record SelectionSnapshot( + AuthoredDraftPublishSelection selection, OffsetDateTime createdAt) { + public SelectionSnapshot { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java new file mode 100644 index 0000000000..680d974385 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -0,0 +1,1679 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashSet; +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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +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.ObjectMapper; + +/** Durable, owner-local persistence for exact Game Design multi-owner Draft commit coordination. */ +@Repository +public class DraftCommitCoordinatorRepository { + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String OWNER_RESULT_TABLE = "game_design_draft_commit_owner_result"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + private static final String APPLICATION_SLOT_TABLE = "game_design_draft_commit_application_slot"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String VISIBILITY_TABLE = "game_design_draft_commit_visibility"; + private static final String PUBLISH_SELECTION_TABLE = + "game_design_authored_draft_publish_selection"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Comparator APPLIED_EPOCH_ORDER = + Comparator.comparing(AppliedEpoch::aggregateType) + .thenComparing(AppliedEpoch::aggregateId) + .thenComparing(AppliedEpoch::scopeType) + .thenComparing(AppliedEpoch::scopeId); + + private final DSLContext dsl; + private final GameDesignDraftTerminalOutcomeRepository terminalOutcomes; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborator only; no resources are acquired and no finalizer is used.") + public DraftCommitCoordinatorRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.terminalOutcomes = new GameDesignDraftTerminalOutcomeRepository(dsl); + } + + /** + * Durably claims one complete immutable request binding and initializes every required owner. An + * exact replay performs no writes; either identity reused with changed binding data conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + CommitRecord existing = findCommit(binding, true); + if (existing != null) { + requireExactBinding(binding, existing.binding()); + return snapshot(existing); + } + + int inserted = + dsl.execute( + "INSERT INTO " + + COMMIT_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, request_id, commit_id, base_commit_id, input_digest, " + + "binding_json, workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'QUEUED') " + // Request and commit are independent immutable identities; suppress either unique + // collision in PostgreSQL so the transaction remains readable for exact readback. + + "ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.target().gameDesignVersionRowId(), + binding.target().gameDesignVersionTenantKey(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); + + if (inserted == 0) { + CommitRecord concurrent = findCommit(binding, true); + if (concurrent == null) { + throw new DraftCommitIdentityConflictException( + "Draft commit identity conflicts with another immutable request"); + } + requireExactBinding(binding, concurrent.binding()); + return snapshot(concurrent); + } + + for (Owner owner : binding.requiredOwners()) { + dsl.execute( + "INSERT INTO " + + OWNER_RESULT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, owner, status) " + + "VALUES (?, ?, ?, ?, 'NOT_ATTEMPTED')", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + } + CommitRecord persisted = findCommit(binding, true); + if (persisted == null) { + throw new IllegalStateException("Durable Draft commit binding disappeared after insert"); + } + requireExactBinding(binding, persisted.binding()); + return snapshot(persisted); + } + + /** + * Claims a complete Account operation alongside its coordinator binding before dispatch. The + * Account bytes are exact source material only; this storage operation does not authenticate them + * or authorize owner writes. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim( + DraftCommitBinding binding, DraftAuthorizationFenceBinding originalAccountBinding) { + requireWritableReadCommittedTransaction(); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(originalAccountBinding, binding); + LockedVersion lockedVersion = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + terminalOutcomes.validateClaim(operation, lockedVersion); + CommitSnapshot snapshot = claim(binding); + terminalOutcomes.claim(operation, lockedVersion); + return snapshot; + } + + /** Reads one durable binding and its exact per-owner status vector. */ + public Optional read(DraftCommitBinding.TargetProof target, UUID requestId) { + requireTargetAndRequest(target, requestId); + CommitRecord record = findCommit(target, requestId, false); + return record == null ? Optional.empty() : Optional.of(snapshot(record)); + } + + /** Reads the current active dispatch/recovery slot for one canonical Version. */ + public Optional readApplicationSlot(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record record = findSlot(target, false); + return record == null ? Optional.empty() : Optional.of(toApplicationSlot(record)); + } + + /** + * Claims the single active owner-application slot for this canonical Version. The persisted + * binding remains queued if another exact commit currently owns the slot. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public ApplicationSlot claimApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + CommitRecord commit = findCommit(binding, true); + if (commit == null) { + throw new DraftCommitNotFoundException( + "Draft commit must be durably claimed before slot claim"); + } + requireExactBinding(binding, commit.binding()); + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "A terminal Draft commit cannot reclaim its slot"); + } + Record existing = findSlot(binding.target(), true); + if (existing != null) { + ApplicationSlot slot = toApplicationSlot(existing); + requireSameSlot(binding, slot); + return slot; + } + int inserted = + dsl.execute( + "INSERT INTO " + + APPLICATION_SLOT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + Record persisted = findSlot(binding.target(), true); + if (persisted == null) { + throw new DraftCommitStateConflictException( + "Another coordinated Draft commit currently owns the Version application slot"); + } + ApplicationSlot slot = toApplicationSlot(persisted); + requireSameSlot(binding, slot); + if (inserted == 1 && slot.claimedAt() == null) { + throw new IllegalStateException("Draft commit application slot lacks durable claim time"); + } + return slot; + } + + /** Marks an owner dispatch in progress before the caller makes any remote owner call. */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState markOwnerInProgress(DraftCommitBinding binding, Owner owner) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireExactCommitInTransaction(binding); + requireActiveSlot(binding); + OwnerState current = requireOwnerState(binding, owner, true); + if (current.status() == OwnerStatus.IN_PROGRESS) { + return current; + } + if (current.status() != OwnerStatus.NOT_ATTEMPTED) { + throw new DraftCommitStateConflictException( + "Only a not-yet-attempted owner can enter IN_PROGRESS"); + } + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = 'IN_PROGRESS', updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = 'NOT_ATTEMPTED'", + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner status changed concurrently"); + } + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + } + return requireOwnerState(binding, owner, false); + } + + /** + * Retains one full owner result. UNKNOWN remains unresolved and can only be resolved through an + * exact later APPLIED/REJECTED result for the same commit and binding digest. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState recordOwnerOutcome(DraftCommitBinding binding, OwnerOutcome outcome) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(outcome, "outcome"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireExactCommitInTransaction(binding); + requireOutcomeMatches(binding, outcome); + OwnerState current = requireOwnerState(binding, outcome.owner(), true); + if (current.outcome().filter(outcome::equals).isPresent()) { + return current; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + if (current.status() != OwnerStatus.IN_PROGRESS && current.status() != OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "A Draft owner outcome cannot replace its durable prior result"); + } + if (current.status() == OwnerStatus.UNKNOWN && outcome.status() == OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "UNKNOWN remains unresolved until exact owner readback supplies a terminal result"); + } + String appliedUnitsJson = + outcome.status() == OwnerStatus.UNKNOWN + ? null + : canonicalJson(outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = ?, result_commit_id = ?, result_binding_digest = ?, " + + "result_identity = ?, result_bytes = ?, applied_units_json = ?, updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = ?", + outcome.status().name(), + outcome.commitId(), + outcome.bindingDigest(), + outcome.resultIdentity(), + outcome.resultBytes(), + appliedUnitsJson, + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + outcome.owner().name(), + current.status().name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner result changed concurrently"); + } + updateWorkflowStateAfterOwnerOutcome(binding, outcome); + return requireOwnerState(binding, outcome.owner(), false); + } + + /** + * Canonical source-aware fence handoff. The caller still supplies independently verified owner + * proof; both complete source snapshots become visible in this same owner transaction. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceSourceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + var sources = new GameDesignSourceRepository(dsl); + if (sources.readGenesis(binding.target()).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + VisibilityFence fence = advanceVisibilityFence(binding, coordinatorProof); + sources.captureSynchronized(binding); + return fence; + } + + /** + * Advances the internal synchronized visibility record only from the complete exact APPLIED + * result vector. This storage primitive is intentionally not wired to an owner producer or read + * API; callers must validate each remote producer's authority before invoking it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(coordinatorProof, "coordinatorProof"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + if (!coordinatorProof.matches(binding)) { + throw new DraftCommitIdentityConflictException( + "Visibility fence requires coordinator proof for this exact Draft binding"); + } + List ownerStates = lockAndReadOwnerStates(binding); + coordinatorProof.requireSameOutcomes(ownerStates); + String resultVectorJson = exactAppliedResultVector(binding, ownerStates); + VisibilityFence existing = findVisibilityFence(binding, false); + if (existing != null) { + if (!existing.inputDigest().equals(binding.digest()) + || !existing.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A Draft commit visibility fence already retains different owner evidence"); + } + terminalOutcomes.recordCommitted(binding, existing, resultVectorJson, false); + return existing; + } + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Terminal Draft commit has no matching immutable visibility fence"); + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + int inserted = + dsl.execute( + "INSERT INTO " + + VISIBILITY_FENCE_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + resultVectorJson); + VisibilityFence persisted = findVisibilityFence(binding, false); + if (persisted == null) { + throw new IllegalStateException("Draft visibility fence insert returned no persisted row"); + } + if (inserted == 0) { + if (!persisted.inputDigest().equals(binding.digest()) + || !persisted.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A concurrent Draft visibility fence retained different owner evidence"); + } + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "A pre-existing visibility fence is not paired with synchronized workflow state"); + } + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, false); + return persisted; + } + dsl.execute( + "INSERT INTO " + + VISIBILITY_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (canonical_tenant_id, canonical_version_id) " + + "DO UPDATE SET request_id = EXCLUDED.request_id, commit_id = EXCLUDED.commit_id, " + + "input_digest = EXCLUDED.input_digest, updated_at = EXCLUDED.updated_at", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest()); + updateWorkflowState(binding, WorkflowState.SYNCHRONIZED); + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, true); + return persisted; + } + + /** + * Reads the current internal visibility pointer without claiming that downstream reads use it. + */ + public Optional readVisibilityFence(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record pointer = + dsl.fetchOne( + "SELECT request_id, commit_id FROM " + + VISIBILITY_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (pointer == null) { + return Optional.empty(); + } + UUID requestId = pointer.get("request_id", UUID.class); + UUID commitId = pointer.get("commit_id", UUID.class); + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + if (fence == null) { + throw new IllegalStateException("Draft visibility pointer lacks its immutable fence record"); + } + return Optional.of(toVisibilityFence(target, requestId, commitId, fence)); + } + + /** + * Captures only an explicitly selected current synchronized commit while the caller's publication + * transaction owns the exact Version row lock. It does not authorize publication or assert any + * remote freeze/participant result. + */ + PublicationEvidence requireSynchronizedPublicationEvidence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, String inputDigest) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(target); + requireDraftVersion(version); + if (findSlot(target, false) != null) { + throw new DraftCommitStateConflictException( + "An active owner application prevents authored Draft publication selection"); + } + + CommitRecord commit = findCommit(target, requestId, true); + if (commit == null + || !commit.binding().commitId().equals(commitId) + || !commit.binding().digest().equals(inputDigest)) { + throw new DraftCommitIdentityConflictException( + "Selected authored Draft commit identity or digest does not match durable input"); + } + if (commit.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "Only an explicitly selected synchronized authored Draft commit can be published"); + } + List ownerStates = lockAndReadOwnerStates(commit.binding()); + String exactVector = exactAppliedResultVector(commit.binding(), ownerStates); + VisibilityFence fence = findVisibilityFence(commit.binding(), true); + if (fence == null + || !fence.inputDigest().equals(inputDigest) + || !fence.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit lacks its exact complete synchronized result fence"); + } + VisibilityFence current = + readVisibilityFence(target) + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Selected authored Draft commit is not the current synchronized fence")); + if (!current.requestId().equals(requestId) + || !current.commitId().equals(commitId) + || !current.inputDigest().equals(inputDigest) + || !current.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit is stale relative to the current synchronized fence"); + } + return new PublicationEvidence(commit.binding(), fence); + } + + /** + * Releases the Version application slot after complete success, definite no-application + * rejection, or exact final-abort evidence with every owner definitive. Unresolved outcomes and + * partial application without that final-abort proof keep the slot held. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public void releaseApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + Record slotRecord = findSlot(binding.target(), true); + if (commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + requireFinalAbortSlotRelease(binding, commit); + if (slotRecord == null || !isSameSlot(binding, toApplicationSlot(slotRecord))) { + return; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + deleteApplicationSlot(binding); + return; + } + if (slotRecord == null) { + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED) { + return; + } + throw new DraftCommitStateConflictException( + "Draft commit does not own the active Version slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + List outcomes = lockAndReadOwnerStates(binding); + boolean anyApplied = outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean unresolved = + outcomes.stream() + .anyMatch( + state -> + state.status() == OwnerStatus.UNKNOWN + || state.status() == OwnerStatus.IN_PROGRESS); + boolean allApplied = outcomes.stream().allMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean definiteNoApply = + outcomes.stream() + .allMatch( + state -> + state.status() == OwnerStatus.NOT_ATTEMPTED + || state.status() == OwnerStatus.REJECTED) + && outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + if (unresolved || (anyApplied && !allApplied) || (!allApplied && !definiteNoApply)) { + throw new DraftCommitStateConflictException( + "Unresolved or partially applied Draft commit cannot release its Version slot"); + } else if (allApplied) { + VisibilityFence fence = findVisibilityFence(binding, false); + if (commit.workflowState() != WorkflowState.SYNCHRONIZED + || fence == null + || !fence.inputDigest().equals(binding.digest())) { + throw new DraftCommitStateConflictException( + "All-owner Draft application must have its exact synchronized visibility fence first"); + } + } else if (definiteNoApply) { + if (anyApplied) { + throw new DraftCommitStateConflictException( + "A rejected Draft commit with any applied owner requires reconciliation"); + } + if (terminalOutcomes.isAccountBound(binding)) { + throw new DraftCommitStateConflictException( + "An Account-bound Draft commit requires its exact final-abort tombstone and complete owner vector"); + } + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Definite rejected Draft commit is not in an applicable workflow state"); + } + updateWorkflowState(binding, WorkflowState.REJECTED); + } + deleteApplicationSlot(binding); + } + + private void deleteApplicationSlot(DraftCommitBinding binding) { + int deleted = + dsl.execute( + "DELETE FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (deleted != 1) { + throw new DraftCommitStateConflictException( + "Draft Version application slot changed concurrently"); + } + } + + /** + * Stores exact, already-authenticated producer no-commit evidence for a definitive owner vector + * and atomically makes this commit terminally non-publishable. This storage method does not + * authenticate arbitrary bytes; only a future authenticated recovery producer may call it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FinalAbortReceipt recordDefinitiveFinalAbort( + DraftCommitBinding binding, byte[] exactAbortBytes) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(exactAbortBytes, "exactAbortBytes"); + if (exactAbortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + Record slotRecord = findSlot(binding.target(), true); + Record existingAbort = findFinalAbort(binding, true); + if (existingAbort != null) { + requireExactFinalAbort(binding, exactAbortBytes, existingAbort); + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new IllegalStateException( + "Durable final-abort evidence is not paired with terminal nonpublication state"); + } + requireFinalAbortSlotRelease(binding, commit); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, existingAbort), + exactTerminalAbortResultVector(binding, lockAndReadOwnerStates(binding)), + false); + return toFinalAbortReceipt(binding, existingAbort); + } + + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + if (slotRecord == null) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires the active Version application slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Only an unresolved owner-application workflow can record final-abort evidence"); + } + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A commit with a successful visibility fence cannot be finalized as nonpublication"); + } + + List ownerStates = lockAndReadOwnerStates(binding); + requireCompleteTerminalAbortVector(binding, ownerStates); + int inserted = + dsl.execute( + "INSERT INTO " + + FINAL_ABORT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, binding_json, abort_bytes) VALUES (?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + exactAbortBytes.clone()); + Record persisted = findFinalAbort(binding, true); + if (persisted == null) { + throw new IllegalStateException("Final-abort evidence insert returned no durable row"); + } + requireExactFinalAbort(binding, exactAbortBytes, persisted); + if (inserted == 0) { + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Concurrent final-abort evidence has no terminal nonpublication state"); + } + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + false); + return toFinalAbortReceipt(binding, persisted); + } + + updateWorkflowState(binding, WorkflowState.FAILED_NONPUBLICATION); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + true); + return toFinalAbortReceipt(binding, persisted); + } + + private void requireFinalAbortSlotRelease(DraftCommitBinding binding, CommitRecord commit) { + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Only a terminal nonpublication commit can release by final-abort evidence"); + } + Record abort = findFinalAbort(binding, true); + if (abort == null) { + throw new DraftCommitStateConflictException( + "Failed nonpublication state lacks exact durable final-abort evidence"); + } + requireExactFinalAbort(binding, abort.get("abort_bytes", byte[].class), abort); + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A final-aborted Draft commit cannot own a successful visibility fence"); + } + requireCompleteTerminalAbortVector(binding, lockAndReadOwnerStates(binding)); + } + + private void requireCompleteTerminalAbortVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires every exact required owner result"); + } + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); + if (state.status() != OwnerStatus.APPLIED && state.status() != OwnerStatus.REJECTED) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires only exact terminal APPLIED or REJECTED owners"); + } + OwnerOutcome outcome = + state + .outcome() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence requires durable owner result bytes")); + requireOutcomeMatches(binding, outcome); + } + } + + private String exactTerminalAbortResultVector( + DraftCommitBinding binding, List ownerStates) { + requireCompleteTerminalAbortVector(binding, ownerStates); + List> resultVector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); + resultVector.add(ownerResultJson(state.outcome().orElseThrow())); + } + return canonicalJson(resultVector); + } + + private void updateWorkflowStateAfterOwnerOutcome( + DraftCommitBinding binding, OwnerOutcome outcome) { + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + commit = requireCommit(binding, true); + } + if (outcome.status() == OwnerStatus.UNKNOWN) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + return; + } + List states = lockAndReadOwnerStates(binding); + boolean hasApplied = states.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean hasRejected = states.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + boolean hasUnknown = states.stream().anyMatch(state -> state.status() == OwnerStatus.UNKNOWN); + if (hasUnknown || (hasApplied && hasRejected)) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + } + } + + private void updateWorkflowState(DraftCommitBinding binding, WorkflowState state) { + int updated = + dsl.execute( + "UPDATE " + + COMMIT_TABLE + + " SET workflow_state = ?, updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + + "AND workflow_state <> ?", + state.name(), + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + state.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException( + "Draft commit workflow state changed concurrently"); + } + } + + private CommitRecord requireExactCommitInTransaction(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + return requireCommit(binding, true); + } + + private CommitRecord requireCommit(DraftCommitBinding binding, boolean forUpdate) { + Objects.requireNonNull(binding, "binding"); + CommitRecord record = findCommit(binding, forUpdate); + if (record == null) { + throw new DraftCommitNotFoundException("Draft commit binding is missing"); + } + requireExactBinding(binding, record.binding()); + return record; + } + + private CommitRecord findCommit(DraftCommitBinding binding, boolean forUpdate) { + return findCommit(binding.target(), binding.requestId(), forUpdate); + } + + private CommitRecord findCommit( + DraftCommitBinding.TargetProof target, UUID requestId, boolean forUpdate) { + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?" + + suffix, + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId); + if (row == null) { + return null; + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!target.equals(binding.target()) + || !requestId.equals(binding.requestId()) + || !row.get("commit_id", UUID.class).equals(binding.commitId()) + || !row.get("base_commit_id", String.class).equals(binding.baseCommitId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(binding.target().gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(binding.target().gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(binding.target().sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class) + .equals(binding.target().sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class) + .equals(binding.target().sourceProvenanceKind())) { + throw new IllegalStateException( + "Draft commit indexed identity differs from its exact JSON binding"); + } + return new CommitRecord( + binding, + WorkflowState.valueOf(row.get("workflow_state", String.class)), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private CommitSnapshot snapshot(CommitRecord record) { + return new CommitSnapshot(record, readOwnerStates(record.binding(), false)); + } + + private List lockAndReadOwnerStates(DraftCommitBinding binding) { + return readOwnerStates(binding, true); + } + + private List readOwnerStates(DraftCommitBinding binding, boolean forUpdate) { + List states = + dsl + .fetch( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? ORDER BY owner" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()) + .stream() + .map(this::toOwnerState) + .toList(); + Map byOwner = new EnumMap<>(Owner.class); + for (OwnerState state : states) { + if (byOwner.put(state.owner(), state) != null) { + throw new IllegalStateException("Duplicate durable Draft owner status row"); + } + } + if (!byOwner.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new IllegalStateException( + "Durable Draft owner status set differs from its complete binding"); + } + return binding.requiredOwners().stream().map(byOwner::get).toList(); + } + + private OwnerState requireOwnerState(DraftCommitBinding binding, Owner owner, boolean forUpdate) { + Objects.requireNonNull(owner, "owner"); + if (!binding.requiredOwners().contains(owner)) { + throw new DraftCommitStateConflictException( + "Owner is not in this Draft commit's required set"); + } + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ?" + + suffix, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (row == null) { + throw new IllegalStateException("Required Draft owner status row is missing"); + } + return toOwnerState(row); + } + + private OwnerState toOwnerState(Record row) { + Owner owner = Owner.valueOf(row.get("owner", String.class)); + OwnerStatus status = OwnerStatus.valueOf(row.get("status", String.class)); + UUID resultCommitId = row.get("result_commit_id", UUID.class); + String digest = row.get("result_binding_digest", String.class); + String resultIdentity = row.get("result_identity", String.class); + byte[] resultBytes = row.get("result_bytes", byte[].class); + String appliedUnitsJson = row.get("applied_units_json", String.class); + OwnerOutcome outcome = null; + if (resultCommitId != null || digest != null || resultIdentity != null || resultBytes != null) { + if (resultCommitId == null || digest == null) { + throw new IllegalStateException("Draft owner result has incomplete commit identity"); + } + List epochs = + appliedUnitsJson == null ? List.of() : parseAppliedEpochs(appliedUnitsJson); + outcome = + new OwnerOutcome( + owner, status, resultCommitId, digest, resultIdentity, resultBytes, epochs); + } + return new OwnerState( + owner, + status, + Optional.ofNullable(outcome), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private List parseAppliedEpochs(String appliedUnitsJson) { + try { + List epochs = new ArrayList<>(); + for (tools.jackson.databind.JsonNode node : JSON.readTree(appliedUnitsJson)) { + epochs.add( + new AppliedEpoch( + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"), + requiredText(node, "resultingEpoch"))); + } + if (!canonicalJson(epochs.stream().map(this::appliedEpochJson).toList()) + .equals(appliedUnitsJson)) { + throw new IllegalStateException("Persisted Draft owner epoch vector is not canonical"); + } + return List.copyOf(epochs); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Draft owner epoch vector is corrupt", exception); + } + } + + private Record findSlot(DraftCommitBinding.TargetProof target, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + } + + private ApplicationSlot toApplicationSlot(Record row) { + return new ApplicationSlot( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("request_id", UUID.class), + row.get("commit_id", UUID.class), + row.get("claimed_at", OffsetDateTime.class)); + } + + private void requireActiveSlot(DraftCommitBinding binding) { + Record row = findSlot(binding.target(), true); + if (row == null) { + throw new DraftCommitStateConflictException( + "Owner dispatch requires the durable Version slot"); + } + requireSameSlot(binding, toApplicationSlot(row)); + } + + private static boolean isSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + return slot.canonicalTenantId().equals(binding.target().canonicalTenantId()) + && slot.canonicalVersionId().equals(binding.target().canonicalVersionId()) + && slot.requestId().equals(binding.requestId()) + && slot.commitId().equals(binding.commitId()); + } + + private static void requireSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + if (!isSameSlot(binding, slot)) { + throw new DraftCommitStateConflictException( + "Another exact Draft commit owns the Version application slot"); + } + } + + private VisibilityFence findVisibilityFence(DraftCommitBinding binding, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + return row == null + ? null + : toVisibilityFence(binding.target(), binding.requestId(), binding.commitId(), row); + } + + private Record findFinalAbort(DraftCommitBinding binding, boolean forUpdate) { + return dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes, created_at FROM " + + FINAL_ABORT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + } + + private void requireExactFinalAbort( + DraftCommitBinding binding, byte[] expectedAbortBytes, Record row) { + if (!binding.digest().equals(row.get("input_digest", String.class)) + || !binding.canonicalJson().equals(row.get("binding_json", String.class)) + || !Arrays.equals(expectedAbortBytes, row.get("abort_bytes", byte[].class))) { + throw new DraftCommitIdentityConflictException( + "Final-abort identity was reused with changed binding or exact evidence bytes"); + } + } + + private FinalAbortReceipt toFinalAbortReceipt(DraftCommitBinding binding, Record row) { + requireExactFinalAbort(binding, row.get("abort_bytes", byte[].class), row); + return new FinalAbortReceipt( + binding, row.get("abort_bytes", byte[].class), row.get("created_at", OffsetDateTime.class)); + } + + private VisibilityFence toVisibilityFence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, Record row) { + return new VisibilityFence( + target, + requestId, + commitId, + row.get("input_digest", String.class), + row.get("result_vector_json", String.class), + row.get("created_at", OffsetDateTime.class)); + } + + private String exactAppliedResultVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException("Complete Draft owner result vector is required"); + } + List> resultVector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Required Draft owner result is missing")); + OwnerOutcome outcome = state.outcome().orElse(null); + if (state.status() != OwnerStatus.APPLIED || outcome == null) { + throw new DraftCommitStateConflictException( + "Draft visibility cannot advance before every required owner is exactly APPLIED"); + } + requireOutcomeMatches(binding, outcome); + List expected = binding.affectedUnits(owner); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result does not prove the complete bound affected tuple set"); + } + resultVector.add(ownerResultJson(outcome)); + } + return canonicalJson(resultVector); + } + + private Map ownerResultJson(OwnerOutcome outcome) { + Map item = new LinkedHashMap<>(); + item.put("owner", outcome.owner().name()); + item.put("status", outcome.status().name()); + item.put("commitId", outcome.commitId().toString()); + item.put("bindingDigest", outcome.bindingDigest()); + item.put("resultIdentity", outcome.resultIdentity()); + item.put( + "resultBytesBase64", + outcome.resultBytes() == null + ? "" + : Base64.getEncoder().encodeToString(outcome.resultBytes())); + item.put( + "appliedEpochs", outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + return item; + } + + private Map appliedEpochJson(AppliedEpoch epoch) { + Map item = new LinkedHashMap<>(); + item.put("aggregateType", epoch.aggregateType()); + item.put("aggregateId", epoch.aggregateId()); + item.put("scopeType", epoch.scopeType()); + item.put("scopeId", epoch.scopeId()); + item.put("expectedEpoch", epoch.expectedEpoch()); + item.put("resultingEpoch", epoch.resultingEpoch()); + return item; + } + + private void requireOutcomeMatches(DraftCommitBinding binding, OwnerOutcome outcome) { + if (!binding.requiredOwners().contains(outcome.owner()) + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest())) { + throw new DraftCommitIdentityConflictException( + "Draft owner outcome is not bound to this exact commit and full input digest"); + } + if (outcome.status() == OwnerStatus.APPLIED) { + List expected = binding.affectedUnits(outcome.owner()); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result omitted a declared aggregate/scope epoch tuple"); + } + for (AppliedEpoch actualEpoch : outcome.appliedEpochs()) { + if (new BigInteger(actualEpoch.resultingEpoch()) + .compareTo(new BigInteger(actualEpoch.expectedEpoch())) + <= 0) { + throw new DraftCommitStateConflictException( + "Draft owner result does not exactly advance every declared tuple"); + } + } + } else if (!outcome.appliedEpochs().isEmpty()) { + throw new DraftCommitStateConflictException( + "Only an APPLIED owner result may report advanced aggregate/scope epochs"); + } + } + + private boolean hasExpectedTuples(List expected, List actual) { + if (expected.size() != actual.size()) { + return false; + } + for (int index = 0; index < expected.size(); index++) { + if (!actual.get(index).matchesExpectedTuple(expected.get(index))) { + return false; + } + } + return true; + } + + private void requireExactBinding(DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitIdentityConflictException( + "Draft request or commit identity was reused with changed complete binding data"); + } + } + + /** + * Locks and proves one canonical Game Design Version before any Draft commit/application lock. + */ + LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) { + requireWritableReadCommittedTransaction(); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + dsl.fetchOne( + "SELECT v.id AS version_row_id, v.tenant_id AS version_tenant_key, " + + "v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, " + + "v.identity_source_provenance_kind, v.version_state, v.version_state_epoch, " + + "v.is_script_only, v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "FOR UPDATE OF v", + canonicalTenantId, + canonicalVersionId); + if (row == null) { + throw new DraftCommitNotFoundException( + "Exact canonical Version and immutable Game source provenance were not found"); + } + Long stateEpoch = row.get("version_state_epoch", Long.class); + if (stateEpoch == null || stateEpoch <= 0) { + throw new DraftCommitStateConflictException( + "Canonical Version lacks a positive persisted version-state epoch"); + } + TargetProof target = + new TargetProof( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("version_row_id", Long.class), + row.get("version_tenant_key", String.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class)); + return new LockedVersion( + target, + row.get("version_state", String.class), + stateEpoch, + row.get("is_script_only", Boolean.class), + row.get("script_patch_version", String.class), + row.get("base_version_id", Long.class)); + } + + private LockedVersion lockVersionTarget(TargetProof expected) { + Objects.requireNonNull(expected, "expected"); + LockedVersion locked = + lockVersionTarget(expected.canonicalTenantId(), expected.canonicalVersionId()); + if (!expected.equals(locked.target())) { + throw new DraftCommitIdentityConflictException( + "Draft binding source proof differs from its locked canonical Version"); + } + return locked; + } + + private static void requireDraftVersion(LockedVersion version) { + if (!"DRAFT".equals(version.versionState())) { + throw new DraftCommitStateConflictException( + "Owner application requires the exact Version to remain DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + Record selection = + dsl.fetchOne( + "SELECT publish_request_id FROM " + + PUBLISH_SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selection != null) { + throw new DraftCommitStateConflictException( + "Authored Draft publication reservation prevents later owner application"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Draft coordinator mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + private static void requireTargetAndRequest( + DraftCommitBinding.TargetProof target, UUID requestId) { + requireTarget(target); + requireNonNil(requestId, "requestId"); + } + + private static void requireTarget(DraftCommitBinding.TargetProof target) { + Objects.requireNonNull(target, "target"); + } + + 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 canonical non-nil UUID"); + } + } + + private static OffsetDateTime now() { + return OffsetDateTime.now(ZoneOffset.UTC); + } + + private String canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return new String(canonical, StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft owner result evidence could not be canonicalized", exception); + } + } + + private static String requiredText(tools.jackson.databind.JsonNode node, String field) { + tools.jackson.databind.JsonNode value = node == null ? null : node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Persisted Draft owner epoch field is missing: " + field); + } + return value.textValue(); + } + + private record CommitRecord( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) {} + + record LockedVersion( + DraftCommitBinding.TargetProof target, + String versionState, + long versionStateEpoch, + boolean scriptOnly, + String scriptPatchVersion, + Long baseVersionId) {} + + public record PublicationEvidence(DraftCommitBinding binding, VisibilityFence visibilityFence) { + public PublicationEvidence { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + } + } + + public enum WorkflowState { + QUEUED, + APPLYING, + RECONCILIATION_REQUIRED, + SYNCHRONIZED, + REJECTED, + FAILED_NONPUBLICATION + } + + public enum OwnerStatus { + NOT_ATTEMPTED, + IN_PROGRESS, + APPLIED, + REJECTED, + UNKNOWN + } + + public record OwnerState( + Owner owner, + OwnerStatus status, + Optional outcome, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + public OwnerState { + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(status, "status"); + outcome = Objects.requireNonNull(outcome, "outcome"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + if ((status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) + != outcome.isEmpty()) { + throw new IllegalArgumentException("Draft owner status/result shape is inconsistent"); + } + if (outcome.isPresent() + && (outcome.orElseThrow().owner() != owner || outcome.orElseThrow().status() != status)) { + throw new IllegalArgumentException( + "Draft owner result identity differs from its status row"); + } + } + } + + public record CommitSnapshot( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt, + Map ownerStates) { + private CommitSnapshot(CommitRecord record, List states) { + this( + record.binding(), + record.workflowState(), + record.createdAt(), + record.updatedAt(), + ownerStateMap(states)); + } + + public CommitSnapshot { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(workflowState, "workflowState"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + ownerStates = Map.copyOf(ownerStates); + } + + private static Map ownerStateMap(List states) { + Map result = new EnumMap<>(Owner.class); + states.forEach(state -> result.put(state.owner(), state)); + return result; + } + } + + public record ApplicationSlot( + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID requestId, + UUID commitId, + OffsetDateTime claimedAt) { + public ApplicationSlot { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(claimedAt, "claimedAt"); + } + } + + public record VisibilityFence( + DraftCommitBinding.TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) { + public VisibilityFence { + Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(inputDigest, "inputDigest"); + Objects.requireNonNull(resultVectorJson, "resultVectorJson"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } + + /** Exact immutable producer evidence that a commit is fenced from any later GD commit. */ + public record FinalAbortReceipt( + DraftCommitBinding binding, byte[] abortBytes, OffsetDateTime createdAt) { + public FinalAbortReceipt { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(abortBytes, "abortBytes"); + if (abortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + abortBytes = abortBytes.clone(); + Objects.requireNonNull(createdAt, "createdAt"); + } + + @Override + public byte[] abortBytes() { + return abortBytes.clone(); + } + } + + public record AppliedEpoch( + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch, + String resultingEpoch) { + public AppliedEpoch { + requireResultText(aggregateType, "aggregateType"); + requireResultText(aggregateId, "aggregateId"); + requireResultText(scopeType, "scopeType"); + requireResultText(scopeId, "scopeId"); + requireDecimal(expectedEpoch, "expectedEpoch"); + requireDecimal(resultingEpoch, "resultingEpoch"); + } + + private boolean matchesExpectedTuple(AffectedUnit expected) { + return aggregateType.equals(expected.aggregateType()) + && aggregateId.equals(expected.aggregateId()) + && scopeType.equals(expected.scopeType()) + && scopeId.equals(expected.scopeId()) + && expectedEpoch.equals(expected.expectedEpoch()); + } + } + + /** + * Internal handoff token for the future coordinator after every authenticated owner producer has + * been validated. Its package-private constructor deliberately leaves this storage slice unwired; + * a repository can persist a fence only when a same-package coordinator supplies the exact + * durable owner outcomes it has independently verified. + */ + public static final class CoordinatorProof { + private final DraftCommitBinding binding; + private final List outcomes; + + CoordinatorProof(DraftCommitBinding binding, List outcomes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.outcomes = List.copyOf(outcomes); + } + + private boolean matches(DraftCommitBinding candidate) { + return binding.equals(candidate); + } + + private void requireSameOutcomes(List states) { + Map verified = new EnumMap<>(Owner.class); + for (OwnerOutcome outcome : outcomes) { + if (outcome.status() != OwnerStatus.APPLIED + || verified.put(outcome.owner(), outcome) != null) { + throw new DraftCommitStateConflictException( + "Coordinator proof must contain one exact APPLIED result per required owner"); + } + } + if (!verified.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new DraftCommitStateConflictException( + "Coordinator proof omits or adds a required Draft owner"); + } + for (OwnerState state : states) { + OwnerOutcome outcome = verified.get(state.owner()); + if (state.status() != OwnerStatus.APPLIED + || outcome == null + || state.outcome().isEmpty() + || !state.outcome().orElseThrow().equals(outcome)) { + throw new DraftCommitStateConflictException( + "Coordinator proof differs from the exact durable owner result row"); + } + } + } + } + + /** Immutable copy of an owner's full terminal or uncertain result evidence. */ + public static final class OwnerOutcome { + private final Owner owner; + private final OwnerStatus status; + private final UUID commitId; + private final String bindingDigest; + private final String resultIdentity; + private final byte[] resultBytes; + private final List appliedEpochs; + + public OwnerOutcome( + Owner owner, + OwnerStatus status, + UUID commitId, + String bindingDigest, + String resultIdentity, + byte[] resultBytes, + List appliedEpochs) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.status = Objects.requireNonNull(status, "status"); + if (status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) { + throw new IllegalArgumentException( + "OwnerOutcome must carry an observed owner result state"); + } + requireNonNil(commitId, "commitId"); + this.commitId = commitId; + this.bindingDigest = Objects.requireNonNull(bindingDigest, "bindingDigest"); + if (!bindingDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("bindingDigest must be a canonical SHA-256 digest"); + } + if ((resultIdentity == null) != (resultBytes == null)) { + throw new IllegalArgumentException( + "Owner result identity and exact result bytes must be paired"); + } + if (status == OwnerStatus.APPLIED || status == OwnerStatus.REJECTED) { + requireResultText(resultIdentity, "resultIdentity"); + } else if (resultIdentity != null) { + requireResultText(resultIdentity, "resultIdentity"); + } + this.resultIdentity = resultIdentity; + this.resultBytes = resultBytes == null ? null : resultBytes.clone(); + Objects.requireNonNull(appliedEpochs, "appliedEpochs"); + List epochCopy = new ArrayList<>(appliedEpochs); + epochCopy.sort(APPLIED_EPOCH_ORDER); + if (!epochCopy.equals(appliedEpochs)) { + throw new IllegalArgumentException("Applied owner epoch tuples must be in canonical order"); + } + if ((status == OwnerStatus.APPLIED) != !epochCopy.isEmpty()) { + throw new IllegalArgumentException("APPLIED result must contain its complete tuple vector"); + } + this.appliedEpochs = List.copyOf(epochCopy); + } + + public Owner owner() { + return owner; + } + + public OwnerStatus status() { + return status; + } + + public UUID commitId() { + return commitId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public String resultIdentity() { + return resultIdentity; + } + + public byte[] resultBytes() { + return resultBytes == null ? null : resultBytes.clone(); + } + + public List appliedEpochs() { + return appliedEpochs; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof OwnerOutcome result + && owner == result.owner + && status == result.status + && commitId.equals(result.commitId) + && bindingDigest.equals(result.bindingDigest) + && Objects.equals(resultIdentity, result.resultIdentity) + && Arrays.equals(resultBytes, result.resultBytes) + && appliedEpochs.equals(result.appliedEpochs)); + } + + @Override + public int hashCode() { + return Objects.hash( + owner, + status, + commitId, + bindingDigest, + resultIdentity, + Arrays.hashCode(resultBytes), + appliedEpochs); + } + } + + private static void requireDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + private static void requireResultText(String value, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank exact text"); + } + } + + public static class DraftCommitIdentityConflictException extends IllegalStateException { + public DraftCommitIdentityConflictException(String message) { + super(message); + } + + public DraftCommitIdentityConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class DraftCommitStateConflictException extends IllegalStateException { + public DraftCommitStateConflictException(String message) { + super(message); + } + } + + public static final class DraftCommitNotFoundException extends IllegalStateException { + public DraftCommitNotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java new file mode 100644 index 0000000000..535f147e1d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** + * Exact Account operation material paired with the complete Game Design commit binding. + * + *

This value validates identity and canonical bytes only. It does not authenticate the Account + * source evidence or authorize a write; that decision belongs to the protected Account producer. + */ +public final class GameDesignDraftTerminalOperation { + private final DraftAuthorizationFenceBinding accountBinding; + private final DraftCommitBinding gameDesignBinding; + private final byte[] accountBindingBytes; + private final String accountBindingDigest; + + public GameDesignDraftTerminalOperation(DraftAuthorizationFenceBinding accountBinding) { + this(accountBinding, bindingFrom(accountBinding)); + } + + public GameDesignDraftTerminalOperation( + DraftAuthorizationFenceBinding accountBinding, DraftCommitBinding gameDesignBinding) { + this.accountBinding = Objects.requireNonNull(accountBinding, "accountBinding"); + this.gameDesignBinding = Objects.requireNonNull(gameDesignBinding, "gameDesignBinding"); + this.accountBindingBytes = accountBinding.canonicalBytes(); + this.accountBindingDigest = sha256(accountBindingBytes); + if (!Arrays.equals(accountBinding.gameDesignBinding(), gameDesignBinding.canonicalBytes()) + || !accountBinding.inputDigest().equals(gameDesignBinding.digest()) + || !accountBinding.requestId().equals(gameDesignBinding.requestId()) + || !accountBinding.commitId().equals(gameDesignBinding.commitId()) + || !accountBinding.tenantId().equals(gameDesignBinding.target().canonicalTenantId()) + || !accountBinding.versionId().equals(gameDesignBinding.target().canonicalVersionId()) + || !accountBinding.baseCommitId().equals(gameDesignBinding.baseCommitId())) { + throw new IllegalArgumentException( + "Account terminal operation differs from the exact complete Game Design binding"); + } + } + + public DraftAuthorizationFenceBinding accountBinding() { + return accountBinding; + } + + public DraftCommitBinding gameDesignBinding() { + return gameDesignBinding; + } + + public byte[] accountBindingBytes() { + return accountBindingBytes.clone(); + } + + public String accountBindingDigest() { + return accountBindingDigest; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOperation other) { + return other != null + && accountBindingDigest.equals(other.accountBindingDigest) + && Arrays.equals(accountBindingBytes, other.accountBindingBytes) + && gameDesignBinding.digest().equals(other.gameDesignBinding.digest()) + && Arrays.equals( + gameDesignBinding.canonicalBytes(), other.gameDesignBinding.canonicalBytes()); + } + + private static DraftCommitBinding bindingFrom(DraftAuthorizationFenceBinding accountBinding) { + Objects.requireNonNull(accountBinding, "accountBinding"); + return DraftCommitBinding.fromStored( + new String(accountBinding.gameDesignBinding(), StandardCharsets.UTF_8), + accountBinding.inputDigest()); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java new file mode 100644 index 0000000000..9e64a5488b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable final Game Design owner result for one exact Account operation. + * + *

A missing outcome is unresolved, never an abort. The retained owner vector is Game Design's + * internal participant evidence; it is not a substitute for Account's independent World outcome. + * This record is readback data, not an authorization decision or an authenticated RPC receipt. + */ +public final class GameDesignDraftTerminalOutcome { + private static final ObjectMapper JSON = new ObjectMapper(); + + public enum Result { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private final GameDesignDraftTerminalOperation operation; + private final Result result; + private final String ownerResultVectorJson; + private final byte[] finalEvidenceBytes; + private final String finalEvidenceDigest; + private final OffsetDateTime createdAt; + + GameDesignDraftTerminalOutcome( + GameDesignDraftTerminalOperation operation, + Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes, + String finalEvidenceDigest, + OffsetDateTime createdAt) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.result = Objects.requireNonNull(result, "result"); + this.ownerResultVectorJson = + Objects.requireNonNull(ownerResultVectorJson, "ownerResultVectorJson"); + if (ownerResultVectorJson.isBlank()) { + throw new IllegalArgumentException( + "A final outcome requires its complete owner result vector"); + } + validateOwnerResultVector(); + this.finalEvidenceBytes = + Objects.requireNonNull(finalEvidenceBytes, "finalEvidenceBytes").clone(); + if (this.finalEvidenceBytes.length == 0) { + throw new IllegalArgumentException("A final outcome requires exact terminal evidence bytes"); + } + this.finalEvidenceDigest = Objects.requireNonNull(finalEvidenceDigest, "finalEvidenceDigest"); + if (!finalEvidenceDigest.matches("sha256:[0-9a-f]{64}") + || !finalEvidenceDigest.equals( + GameDesignDraftTerminalOperation.sha256(this.finalEvidenceBytes))) { + throw new IllegalArgumentException( + "Terminal evidence digest differs from exact evidence bytes"); + } + if (result == Result.COMMITTED + && !Arrays.equals( + this.finalEvidenceBytes, ownerResultVectorJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Committed terminal evidence must be the exact synchronized owner result vector"); + } + this.createdAt = Objects.requireNonNull(createdAt, "createdAt"); + } + + public GameDesignDraftTerminalOperation operation() { + return operation; + } + + public Result result() { + return result; + } + + public DraftAuthorizationFenceBinding.Owner owner() { + return DraftAuthorizationFenceBinding.Owner.GAME_DESIGN; + } + + /** + * Maps this durable Game Design result to Account's existing canonical owner-readback value. This + * is only a byte-for-byte schema adapter; it does not authenticate the producer or make this + * otherwise unregistered component an authorization source. + */ + public DraftAuthorizationFenceBinding.OwnerReadback toOwnerReadback() { + DraftAuthorizationFenceBinding accountBinding = operation.accountBinding(); + return new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.valueOf(result.name()), + accountBinding.operationId(), + accountBinding.commitId(), + accountBinding.fenceId(), + accountBinding.inputDigest(), + operation.accountBindingBytes(), + finalEvidenceBytes); + } + + public String ownerResultVectorJson() { + return ownerResultVectorJson; + } + + public byte[] finalEvidenceBytes() { + return finalEvidenceBytes.clone(); + } + + public String finalEvidenceDigest() { + return finalEvidenceDigest; + } + + public OffsetDateTime createdAt() { + return createdAt; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOutcome other) { + return other != null + && operation.exactlyMatches(other.operation) + && result == other.result + && ownerResultVectorJson.equals(other.ownerResultVectorJson) + && Arrays.equals(finalEvidenceBytes, other.finalEvidenceBytes) + && finalEvidenceDigest.equals(other.finalEvidenceDigest); + } + + private void validateOwnerResultVector() { + try { + byte[] vectorBytes = ownerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals( + vectorBytes, Rfc8785CanonicalJson.canonicalizeUtf8(ownerResultVectorJson))) { + throw new IllegalArgumentException("Terminal owner result vector is not canonical JSON"); + } + JsonNode vector = JSON.readTree(ownerResultVectorJson); + if (vector == null + || !vector.isArray() + || vector.size() != operation.gameDesignBinding().requiredOwners().size()) { + throw new IllegalArgumentException("Terminal owner result vector is incomplete"); + } + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + Owner expectedOwner = operation.gameDesignBinding().requiredOwners().get(index); + String expectedStatus = result == Result.COMMITTED ? "APPLIED" : null; + if (item == null + || !item.isObject() + || item.size() != 7 + || !text(item, "owner").equals(expectedOwner.name()) + || !text(item, "commitId").equals(operation.gameDesignBinding().commitId().toString()) + || !text(item, "bindingDigest").equals(operation.gameDesignBinding().digest()) + || (expectedStatus != null && !text(item, "status").equals(expectedStatus)) + || (result == Result.DEFINITIVELY_ABORTED + && !ListStatus.TERMINAL.contains(text(item, "status"))) + || !item.path("appliedEpochs").isArray() + || !item.path("resultBytesBase64").isTextual() + || !item.path("resultIdentity").isTextual()) { + throw new IllegalArgumentException( + "Terminal owner result vector differs from its complete commit binding"); + } + } + } catch (java.io.IOException exception) { + throw new IllegalArgumentException( + "Terminal owner result vector is not valid JSON", exception); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Terminal owner result is missing text field " + field); + } + return value.textValue(); + } + + private static final class ListStatus { + private static final java.util.Set TERMINAL = java.util.Set.of("APPLIED", "REJECTED"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java new file mode 100644 index 0000000000..d434024b79 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java @@ -0,0 +1,637 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local durable Account-operation claim and final Game Design outcome readback. + * + *

This class deliberately has no Spring component annotation or RPC registration. It stores + * exact source material and coordinator results only; it neither authenticates Account sources nor + * treats those results as Account's independent owner outcomes. + */ +public final class GameDesignDraftTerminalOutcomeRepository { + private static final String OPERATION_TABLE = "game_design_draft_terminal_operation"; + private static final String OUTCOME_TABLE = "game_design_draft_terminal_outcome"; + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + + private final DSLContext dsl; + + public GameDesignDraftTerminalOutcomeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Retains the exact original Account operation before any owner dispatch. The caller must hold + * the same canonical Version row lock used by coordinator transitions. + */ + GameDesignDraftTerminalOperation claim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + validateClaim(operation, lockedVersion); + DraftCommitBinding binding = operation.gameDesignBinding(); + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return persisted; + } + Record byCommit = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (byCommit != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "A Game Design commit is already claimed by a different Account operation"); + } + + Record commit = + dsl.fetchOne( + "SELECT input_digest, binding_json, workflow_state FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitNotFoundException( + "Game Design commit must be claimed before its Account operation"); + } + DraftCommitBinding storedBinding = + DraftCommitBinding.fromStored( + commit.get("binding_json", String.class), commit.get("input_digest", String.class)); + requireExactGameDesignBinding(binding, storedBinding); + if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "Original Account operation must be retained before owner dispatch begins"); + } + if (!"DRAFT".equals(lockedVersion.versionState())) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation can be newly claimed only while its exact Version is DRAFT"); + } + Record slot = + dsl.fetchOne( + "SELECT 1 FROM game_design_draft_commit_application_slot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (slot != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation must be claimed before the Version dispatch slot is acquired"); + } + + DraftAuthorizationFenceBinding account = operation.accountBinding(); + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, request_id, commit_id, fence_id, actor_account_id, " + + "canonical_tenant_id, canonical_version_id, base_commit_id, expected_draft_epoch, " + + "account_binding_bytes, account_binding_digest, game_design_binding_json, " + + "game_design_input_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.actorAccountId(), + account.tenantId(), + account.versionId(), + account.baseCommitId(), + account.expectedDraftEpoch(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + binding.canonicalJson(), + binding.digest()); + Record persistedRow = findOperation(account.operationId(), true); + if (persistedRow == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity conflicts with a retained Game Design binding"); + } + GameDesignDraftTerminalOperation persisted = toOperation(persistedRow); + requireExactOperation(operation, persisted); + return persisted; + } + + /** + * Fails before the coordinator creates any row if a supplied Account binding is not claimable. + */ + void validateClaim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(lockedVersion, "lockedVersion"); + DraftCommitBinding binding = operation.gameDesignBinding(); + if (!binding.target().equals(lockedVersion.target())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation differs from the same-Version claim lock"); + } + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return; + } + Record byCommit = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (byCommit != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "A Game Design commit is already claimed by a different Account operation"); + } + Record commit = + dsl.fetchOne( + "SELECT input_digest, binding_json, workflow_state FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit != null) { + DraftCommitBinding storedBinding = + DraftCommitBinding.fromStored( + commit.get("binding_json", String.class), commit.get("input_digest", String.class)); + requireExactGameDesignBinding(binding, storedBinding); + if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "Original Account operation must be retained before owner dispatch begins"); + } + } + if (!"DRAFT".equals(lockedVersion.versionState())) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation can be newly claimed only while its exact Version is DRAFT"); + } + Record slot = + dsl.fetchOne( + "SELECT 1 FROM game_design_draft_commit_application_slot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (slot != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation must be claimed before the Version dispatch slot is acquired"); + } + } + + /** Reads the immutable operation claim, whether or not a terminal outcome exists yet. */ + Optional readOperation(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + Record row = findOperation(operationId, false); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + /** + * Reads only an explicitly persisted terminal outcome. Empty means unresolved or unclaimed; it + * never means definitively aborted. + */ + Optional read(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + GameDesignDraftTerminalOperation operation = readOperation(operationId).orElse(null); + if (operation == null) { + return Optional.empty(); + } + Record row = findOutcome(operationId, false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(operation, row)); + } + + /** Exact-binding readback for Account; changed original bytes conflict instead of aliasing. */ + public Optional read(GameDesignDraftTerminalOperation expected) { + Objects.requireNonNull(expected, "expected"); + GameDesignDraftTerminalOperation persisted = + readOperation(expected.accountBinding().operationId()).orElse(null); + if (persisted == null) { + if (findOperation( + expected.gameDesignBinding().target(), + expected.gameDesignBinding().requestId(), + expected.gameDesignBinding().commitId(), + false) + != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design commit is retained under a different Account operation identity"); + } + return Optional.empty(); + } + requireExactOperation(expected, persisted); + Record row = findOutcome(expected.accountBinding().operationId(), false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(persisted, row)); + } + + /** + * Reconstructs only the complete binding already embedded in the original Account bytes, then + * reads its explicit immutable terminal row. Missing operation or result remains unresolved. + */ + public Optional readAccountBound( + byte[] originalAccountBindingBytes) { + requireCommittedReadBoundary(); + if (originalAccountBindingBytes == null || originalAccountBindingBytes.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + DraftAuthorizationFenceBinding accountBinding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBindingBytes.clone()); + return read(new GameDesignDraftTerminalOperation(accountBinding)); + } + + /** + * External Account readback cannot observe rows before the caller's owner transaction commits. + */ + private static void requireCommittedReadBoundary() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account-bound terminal readback requires a committed owner transaction boundary"); + } + } + + /** Records the local committed outcome in the same transaction as synchronized visibility. */ + Optional recordCommitted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.VisibilityFence visibilityFence, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + if (!visibilityFence.target().equals(binding.target()) + || !visibilityFence.requestId().equals(binding.requestId()) + || !visibilityFence.commitId().equals(binding.commitId()) + || !visibilityFence.inputDigest().equals(binding.digest()) + || !visibilityFence.resultVectorJson().equals(exactOwnerResultVectorJson)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Committed terminal evidence differs from the exact synchronized visibility fence"); + } + byte[] evidence = exactOwnerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + + /** Records the local no-commit outcome beside the exact abort tombstone and owner vector. */ + Optional recordAborted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.FinalAbortReceipt abortReceipt, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(abortReceipt, "abortReceipt"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + requireExactGameDesignBinding(binding, abortReceipt.binding()); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + + /** Prevents a late coordinator transition from mutating a definitively aborted operation. */ + void requireNotDefinitivelyAborted(DraftCommitBinding binding) { + Record operation = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operation == null) { + return; + } + Record outcome = findOutcome(operation.get("operation_id", UUID.class), true); + if (outcome != null + && GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED + .name() + .equals(outcome.get("outcome", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "A definitively aborted Account-bound Draft operation cannot accept a late writer"); + } + } + + boolean isAccountBound(DraftCommitBinding binding) { + return findOperation(binding.target(), binding.requestId(), binding.commitId(), false) != null; + } + + private GameDesignDraftTerminalOutcome insertOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + String evidenceDigest = GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes); + if (existing != null) { + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal outcome identity was reused with changed final evidence"); + } + return retained; + } + + int inserted = + dsl.execute( + "INSERT INTO " + + OUTCOME_TABLE + + " (operation_id, outcome, owner_result_vector_json, terminal_evidence_bytes, " + + "terminal_evidence_digest) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + operationId, + result.name(), + ownerResultVectorJson, + finalEvidenceBytes.clone(), + evidenceDigest); + Record persisted = findOutcome(operationId, true); + if (persisted == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result conflicts with another operation identity"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, persisted); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result retained different final evidence"); + } + if (inserted == 0) { + return retained; + } + return retained; + } + + private GameDesignDraftTerminalOutcome requireExistingOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result expectedResult, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + if (existing == null) { + throw new IllegalStateException( + "A retained Game Design terminal fence lacks its atomic Account-bound outcome row"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome expected = + new GameDesignDraftTerminalOutcome( + operation, + expectedResult, + ownerResultVectorJson, + finalEvidenceBytes, + GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes), + retained.createdAt()); + if (!retained.exactlyMatches(expected)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal readback differs from its retained final fence"); + } + return retained; + } + + private Record findOperation(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private Record findOperation( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + } + + private Record findOutcome(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OUTCOME_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private GameDesignDraftTerminalOperation toOperation(Record row) { + byte[] accountBytes = row.get("account_binding_bytes", byte[].class); + String accountDigest = row.get("account_binding_digest", String.class); + DraftAuthorizationFenceBinding account; + try { + account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Account Draft binding is corrupt", exception); + } + if (!GameDesignDraftTerminalOperation.sha256(accountBytes).equals(accountDigest) + || !account.operationId().equals(row.get("operation_id", UUID.class)) + || !account.requestId().equals(row.get("request_id", UUID.class)) + || !account.commitId().equals(row.get("commit_id", UUID.class)) + || !account.fenceId().equals(row.get("fence_id", UUID.class)) + || !account.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !account.tenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !account.versionId().equals(row.get("canonical_version_id", UUID.class)) + || !account.baseCommitId().equals(row.get("base_commit_id", String.class)) + || !account.expectedDraftEpoch().equals(row.get("expected_draft_epoch", String.class))) { + throw new IllegalStateException( + "Stored Account Draft binding differs from its indexed identity"); + } + DraftCommitBinding gameDesignBinding = + DraftCommitBinding.fromStored( + row.get("game_design_binding_json", String.class), + row.get("game_design_input_digest", String.class)); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, gameDesignBinding); + if (!Arrays.equals(accountBytes, operation.accountBindingBytes())) { + throw new IllegalStateException("Persisted Account Draft binding is not canonical"); + } + return operation; + } + + private GameDesignDraftTerminalOutcome toOutcome( + GameDesignDraftTerminalOperation operation, Record row) { + byte[] evidence = row.get("terminal_evidence_bytes", byte[].class); + String evidenceDigest = row.get("terminal_evidence_digest", String.class); + if (!GameDesignDraftTerminalOperation.sha256(evidence).equals(evidenceDigest)) { + throw new IllegalStateException("Persisted terminal evidence digest differs from its bytes"); + } + return new GameDesignDraftTerminalOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.valueOf(row.get("outcome", String.class)), + row.get("owner_result_vector_json", String.class), + evidence, + evidenceDigest, + row.get("created_at", OffsetDateTime.class)); + } + + /** + * Confirms that a returned status row still has its exact durable coordinator terminal fence; + * workflow status alone is never treated as a participant result. + */ + private GameDesignDraftTerminalOutcome readAndVerifyTerminalOutcome( + GameDesignDraftTerminalOperation operation, Record outcomeRow) { + GameDesignDraftTerminalOutcome outcome = toOutcome(operation, outcomeRow); + DraftCommitBinding binding = operation.gameDesignBinding(); + Record commit = + dsl.fetchOne( + "SELECT workflow_state, input_digest, binding_json FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit == null + || !binding.digest().equals(commit.get("input_digest", String.class)) + || !binding.canonicalJson().equals(commit.get("binding_json", String.class))) { + throw new IllegalStateException( + "Game Design terminal outcome lacks its exact retained coordinator commit"); + } + + if (outcome.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (!"SYNCHRONIZED".equals(commit.get("workflow_state", String.class)) + || fence == null + || !binding.digest().equals(fence.get("input_digest", String.class)) + || !outcome.ownerResultVectorJson().equals(fence.get("result_vector_json", String.class)) + || !Arrays.equals( + outcome.finalEvidenceBytes(), + outcome.ownerResultVectorJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException( + "Committed Game Design terminal outcome lacks its exact synchronized visibility fence"); + } + return outcome; + } + + Record abort = + dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes FROM " + + FINAL_ABORT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + Record fence = + dsl.fetchOne( + "SELECT 1 FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (!"FAILED_NONPUBLICATION".equals(commit.get("workflow_state", String.class)) + || abort == null + || !binding.digest().equals(abort.get("input_digest", String.class)) + || !binding.canonicalJson().equals(abort.get("binding_json", String.class)) + || !Arrays.equals(outcome.finalEvidenceBytes(), abort.get("abort_bytes", byte[].class)) + || fence != null) { + throw new IllegalStateException( + "Aborted Game Design terminal outcome lacks its exact final-abort tombstone"); + } + return outcome; + } + + private void requireExactOperation( + GameDesignDraftTerminalOperation expected, GameDesignDraftTerminalOperation actual) { + if (!expected.exactlyMatches(actual)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity was reused with changed original canonical bytes"); + } + } + + private void requireExactGameDesignBinding( + DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Terminal operation differs from its complete canonical Game Design binding"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Game Design terminal mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java new file mode 100644 index 0000000000..e1d831cce1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; + +/** Exact versioned owner evidence frozen when a proposal is reviewed; grants no authorization. */ +public final class GameDesignReviewedBaseEvidence { + public static final String SCHEMA = "game-design-reviewed-draft-base/v1"; + private final TargetProof target; + private final DraftBaseReference reference; + private final byte[] bytes; + private final String digest; + + private GameDesignReviewedBaseEvidence( + TargetProof target, DraftBaseReference reference, byte[] ownerEvidence) { + this.target = Objects.requireNonNull(target, "target"); + this.reference = Objects.requireNonNull(reference, "reference"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, SCHEMA); + frame(out, DraftBaseReference.SCHEMA); + frame(out, reference.kind().name()); + frame(out, reference.canonicalValue()); + frame(out, target.canonicalTenantId().toString()); + frame(out, target.canonicalVersionId().toString()); + frame(out, Long.toString(target.gameDesignVersionRowId())); + frame(out, target.gameDesignVersionTenantKey()); + frame(out, Long.toString(target.sourceGameRowId())); + frame(out, target.sourceGameTenantKey()); + frame(out, target.sourceProvenanceKind()); + DraftAuthorizationFenceBinding.frame(out, ownerEvidence); + bytes = out.toByteArray(); + digest = DraftAuthorizationFenceBinding.digest(bytes); + } + + public static GameDesignReviewedBaseEvidence genesis(GameDesignSourceRepository.Genesis genesis) { + Objects.requireNonNull(genesis, "genesis"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, "shared-policy-command-genesis/v1"); + frame(out, genesis.policy().creationTransactionId()); + DraftAuthorizationFenceBinding.frame(out, genesis.policy().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, genesis.command().canonicalBytes()); + return new GameDesignReviewedBaseEvidence( + genesis.policy().target(), + new DraftBaseReference(DraftBaseReference.Kind.GENESIS, genesis.policy().receiptId()), + out.toByteArray()); + } + + public static GameDesignReviewedBaseEvidence authored( + GameDesignSourceRepository.SynchronizedSources sources, + DraftCommitCoordinatorRepository.CommitSnapshot retained) { + Objects.requireNonNull(sources, "sources"); + Objects.requireNonNull(retained, "retained"); + DraftCommitBinding binding = sources.command().binding(); + if (!binding.equals(retained.binding()) + || retained.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED + || !retained.ownerStates().keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new IllegalArgumentException( + "Exact retained synchronized base and owner vector required"); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, "retained-authored-policy-command-base/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, sources.policy().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, sources.command().canonicalBytes()); + frame(out, Integer.toString(binding.requiredOwners().size())); + for (var owner : binding.requiredOwners()) { + var state = retained.ownerStates().get(owner); + var outcome = state.outcome().orElseThrow(); + if (state.status() != DraftCommitCoordinatorRepository.OwnerStatus.APPLIED + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest()) + || outcome.appliedEpochs().size() != binding.affectedUnits(owner).size() + || binding.affectedUnits(owner).stream() + .anyMatch( + unit -> + outcome.appliedEpochs().stream() + .noneMatch( + epoch -> + epoch.aggregateType().equals(unit.aggregateType()) + && epoch.aggregateId().equals(unit.aggregateId()) + && epoch.scopeType().equals(unit.scopeType()) + && epoch.scopeId().equals(unit.scopeId()) + && epoch.expectedEpoch().equals(unit.expectedEpoch())))) { + throw new IllegalArgumentException("Complete exact APPLIED base owner evidence required"); + } + frame(out, owner.name()); + frame(out, outcome.status().name()); + frame(out, outcome.commitId().toString()); + frame(out, outcome.bindingDigest()); + frame(out, outcome.resultIdentity()); + DraftAuthorizationFenceBinding.frame(out, outcome.resultBytes()); + frame(out, Integer.toString(outcome.appliedEpochs().size())); + for (var epoch : outcome.appliedEpochs()) { + frame(out, epoch.aggregateType()); + frame(out, epoch.aggregateId()); + frame(out, epoch.scopeType()); + frame(out, epoch.scopeId()); + frame(out, epoch.expectedEpoch()); + frame(out, epoch.resultingEpoch()); + } + } + return new GameDesignReviewedBaseEvidence( + binding.target(), + new DraftBaseReference(DraftBaseReference.Kind.AUTHORED_COMMIT, binding.commitId()), + out.toByteArray()); + } + + public TargetProof target() { + return target; + } + + public DraftBaseReference reference() { + return reference; + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public String digest() { + return digest; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + @Override + public boolean equals(Object other) { + return other instanceof GameDesignReviewedBaseEvidence evidence + && Arrays.equals(bytes, evidence.bytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(bytes); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java new file mode 100644 index 0000000000..56439d2c92 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal prerequisite for the canonical reviewed-source ingress; no authentication is implied. + */ +public final class GameDesignReviewedBaseRepository { + private final DSLContext dsl; + private final GameDesignSourceRepository sources; + private final DraftCommitCoordinatorRepository coordinator; + + public GameDesignReviewedBaseRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + sources = new GameDesignSourceRepository(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + /** Resolve exact owner provenance when preparing the immutable review, under the Version lock. */ + public GameDesignReviewedBaseEvidence resolve(TargetProof target, DraftBaseReference reference) { + requireWrite(); + lockDraft(target); + Objects.requireNonNull(reference, "reference"); + if (reference.kind() == DraftBaseReference.Kind.GENESIS) { + var genesis = + sources + .readGenesis(target) + .orElseThrow(() -> new IllegalStateException("REVIEWED_BASE_GENESIS_UNAVAILABLE")); + if (!reference.identity().equals(genesis.policy().receiptId())) { + throw new IllegalArgumentException("REVIEWED_BASE_GENESIS_IDENTITY_CONFLICT"); + } + return GameDesignReviewedBaseEvidence.genesis(genesis); + } + var synchronizedSources = + sources + .readSynchronized(target, reference.identity()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_SOURCE_UNAVAILABLE")); + var binding = synchronizedSources.command().binding(); + var retained = + coordinator + .read(target, binding.requestId()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_COMMIT_UNAVAILABLE")); + if (!reference.identity().equals(binding.commitId())) { + throw new IllegalArgumentException("REVIEWED_BASE_AUTHORED_IDENTITY_CONFLICT"); + } + return GameDesignReviewedBaseEvidence.authored(synchronizedSources, retained); + } + + /** + * Compare the frozen reviewed bytes to actual owner evidence before claiming a new coordinator + * binding. Exact retries compare retained bytes and never re-resolve or replace their provenance. + * Account authorization and semantic affected-set verification remain caller obligations. + */ + public DraftCommitCoordinatorRepository.CommitSnapshot claimReviewed( + DraftCommitBinding binding, GameDesignReviewedBaseEvidence expectedReviewedEvidence) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(expectedReviewedEvidence, "expectedReviewedEvidence"); + var reference = DraftBaseReference.parse(binding.baseCommitId()); + if (!binding.target().equals(expectedReviewedEvidence.target()) + || !reference.equals(expectedReviewedEvidence.reference())) { + throw new IllegalArgumentException("REVIEWED_BASE_BINDING_CONFLICT"); + } + var locked = + coordinator.lockVersionTarget( + binding.target().canonicalTenantId(), binding.target().canonicalVersionId()); + if (!binding.target().equals(locked.target())) { + throw new IllegalArgumentException("REVIEWED_BASE_TARGET_CONFLICT"); + } + Optional existing = read(binding); + if (existing.isPresent()) { + requireExact(expectedReviewedEvidence, existing.orElseThrow()); + return coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + } + // A previously opaque claim cannot be retroactively decorated with invented reviewed evidence. + if (coordinator.read(binding.target(), binding.requestId()).isPresent()) { + throw new IllegalStateException("REVIEWED_BASE_EXISTING_CLAIM_LACKS_EVIDENCE"); + } + var resolved = resolve(binding.target(), reference); + if (!resolved.equals(expectedReviewedEvidence)) { + throw new IllegalArgumentException("REVIEWED_BASE_OWNER_EVIDENCE_CONFLICT"); + } + var result = coordinator.claim(binding); + dsl.execute( + "INSERT INTO game_design_reviewed_draft_base " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest, " + + "binding_json, base_kind, base_identity, base_reference, evidence_schema, " + + "evidence_bytes, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + reference.kind().name(), + reference.identity(), + reference.canonicalValue(), + GameDesignReviewedBaseEvidence.SCHEMA, + resolved.canonicalBytes(), + resolved.digest()); + requireExact(resolved, read(binding).orElseThrow()); + return result; + } + + /** Immutable exact-binding readback, including the original bytes and their versioned digest. */ + public Optional read(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_reviewed_draft_base WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND (request_id = ? OR commit_id = ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var reference = DraftBaseReference.parse(binding.baseCommitId()); + if (!binding.equals( + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class))) + || !reference.kind().name().equals(row.get("base_kind", String.class)) + || !reference.identity().equals(row.get("base_identity", java.util.UUID.class)) + || !reference.canonicalValue().equals(row.get("base_reference", String.class)) + || !GameDesignReviewedBaseEvidence.SCHEMA.equals( + row.get("evidence_schema", String.class))) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + } + var result = + new ReviewedBaseReadback( + row.get("evidence_bytes", byte[].class), row.get("evidence_digest", String.class)); + return Optional.of(result); + } + + /** Require original immutable review provenance for source writes and publication consumption. */ + public ReviewedBaseReadback requireRetained(DraftCommitBinding binding) { + var retained = + read(binding) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE")); + var commit = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow( + () -> new IllegalStateException("REVIEWED_BASE_AUTHORED_COMMIT_UNAVAILABLE")); + if (!binding.equals(commit.binding())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + } + return retained; + } + + private void lockDraft(TargetProof target) { + Objects.requireNonNull(target, "target"); + var version = + coordinator.lockVersionTarget(target.canonicalTenantId(), target.canonicalVersionId()); + if (!target.equals(version.target()) + || !"DRAFT".equals(version.versionState()) + || version.scriptOnly() + || version.baseVersionId() != null + || version.scriptPatchVersion() != null) { + throw new IllegalArgumentException("REVIEWED_BASE_EXACT_FULL_DRAFT_REQUIRED"); + } + } + + private static void requireExact( + GameDesignReviewedBaseEvidence expected, ReviewedBaseReadback stored) { + if (!expected.digest().equals(stored.digest()) + || !Arrays.equals(expected.canonicalBytes(), stored.canonicalBytes())) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_EVIDENCE_CONFLICT"); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Reviewed base requires caller-owned writable READ_COMMITTED transaction"); + } + } + + public record ReviewedBaseReadback(byte[] canonicalBytes, String digest) { + public ReviewedBaseReadback { + canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(digest)) { + throw new IllegalArgumentException("REVIEWED_BASE_STORED_DIGEST_CONFLICT"); + } + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java index 8a4f73b3ba..5b44c7f491 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java @@ -7,8 +7,30 @@ public record PublishParticipantDigestDto( String appliedCommitId, String contentDigest, Integer digestSchemaVersion, + String abilitySchemaDigest, String errorCode, String errorMessage) { + public PublishParticipantDigestDto( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String errorCode, + String errorMessage) { + this( + participantKey, + scopeValue, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + null, + errorCode, + errorMessage); + } + /** * Preserve the full-version construction shape while the typed patch scope is introduced. * Full-version digests have no base version and therefore keep this field null. @@ -28,6 +50,7 @@ public PublishParticipantDigestDto( appliedCommitId, contentDigest, digestSchemaVersion, + null, errorCode, errorMessage); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index a510179f25..b8cd545f21 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -2,6 +2,9 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( Long id, @@ -17,14 +20,30 @@ public record PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); participantDigests = List.copyOf(participantDigests == null ? List.of() : participantDigests); commandDefinitions = List.copyOf(commandDefinitions == null ? List.of() : commandDefinitions); + if ((manifestSchemaVersion == null) != (artifactDigests == null)) { + throw new IllegalArgumentException( + "Manifest schema and artifact proof must be present together"); + } + artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); + if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Selector evidence requires bundle v2 and is mandatory for v2"); + } } + /** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */ public PublishedReleaseBundleDto( Long id, String tenantId, @@ -35,10 +54,58 @@ public PublishedReleaseBundleDto( String manifestHash, List requiredManifestAssetKeys, List participantDigests, + List commandDefinitions, String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { + this( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + commandDefinitions, + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests, + null); + } + + public PublishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { this( id, tenantId, @@ -53,6 +120,11 @@ public PublishedReleaseBundleDto( generationConfigRevision, scriptOnly, scriptPatchVersion, - publishedAt); + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java index 357d46c8e8..2626699e67 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java @@ -5,6 +5,9 @@ @Data public class LaunchDescriptor { + public static final String OUTCOME_SUCCESS = "SUCCESS"; + public static final String OUTCOME_FAILED = "FAILED"; + private Long id; private String launchDescriptorId; private String tenantId; @@ -19,5 +22,18 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String worldSlug; + private String authoredWorldSourceOperationId; + private String authoredWorldSourceEvidenceDigest; + private String requestDigest; + private String resultDigest; + private String originalRequestJson; + private String sourceEvidenceJson; + private String outcomeStatus = OUTCOME_SUCCESS; + private String failureCode; + private String failureMessage; private LocalDateTime createdAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java index ab51eeb0da..b9ef9861f4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java @@ -12,6 +12,7 @@ public class PublishAttempt { private String publishWorkflowId; private PublishType publishType; private PublishAttemptStatus status = PublishAttemptStatus.PENDING; + private long revision = 1L; private Long versionId; private int versionNumber; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java index 9fd7a4f5ed..83853a7800 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java @@ -1,21 +1,28 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; @Data public class PublishedReleaseBundle { private Long id; + private String publishedReleaseBundleRef; private String tenantId; private Long versionId; + private UUID canonicalTenantId; + private UUID canonicalVersionId; private int versionNumber; private String attestationSchemaVersion; private String publishWorkflowId; private String manifestHash; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; private String generationConfigRevision; private String requiredManifestAssetKeysJson; private String participantDigestsJson = "[]"; private String commandDefinitionsJson = "[]"; + private String worldPublishedStartLocationEvidenceJson; private boolean scriptOnly; private String scriptPatchVersion; private LocalDateTime publishedAt = LocalDateTime.now(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java index 9be9dded8b..760243d04c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; @@ -8,6 +9,11 @@ public class Version { private Long id; private String tenantId; + private UUID canonicalVersionId; + private UUID canonicalTenantId; + private Long identitySourceGameRowId; + private String identitySourceGameTenantKey; + private String identitySourceProvenanceKind; private int versionNumber; private VersionLifecycleState versionState = VersionLifecycleState.DRAFT; private Long versionStateEpoch = 1L; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java index 0d026b3526..90ad7a65a2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java @@ -17,5 +17,9 @@ public class VersionAssetArtifact { private String lastErrorCode; private String lastErrorMessage; private String exportedManifestAssetKeysJson = "[]"; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; + private String publishedObjectProofsJson; + private Long candidateSnapshotVersionId; private LocalDateTime updatedAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java new file mode 100644 index 0000000000..65f7993ee8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact staged command-source application evidence, separate from the combined owner outcome. */ +public record CommandApplication( + DraftCommitBinding binding, + UUID inheritedCommitId, + String expectedEpoch, + List mutations, + CommandSnapshot snapshot) { + public CommandApplication { + Objects.requireNonNull(binding, "binding"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + requireCounter(expectedEpoch); + mutations = List.copyOf(Objects.requireNonNull(mutations, "mutations")); + if (mutations.isEmpty()) { + throw new IllegalArgumentException( + "Command application must contain explicit command mutations"); + } + if (!CommandSource.mutationsFromStored(CommandSource.mutationsJson(mutations)) + .equals(mutations)) { + throw new IllegalArgumentException( + "Command application mutations must retain canonical revision order"); + } + Objects.requireNonNull(snapshot, "snapshot"); + if (!binding.equals(snapshot.binding()) + || !Objects.equals(inheritedCommitId, snapshot.inheritedCommitId()) + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch()) + || mutations.stream() + .anyMatch(mutation -> !binding.commitId().equals(mutation.commitId()))) { + throw new IllegalArgumentException( + "Command application evidence differs from its exact binding"); + } + List commandScopes = + binding.affectedUnits(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(CommandApplication::isCommandScope) + .toList(); + if (commandScopes.size() != 1 + || !expectedEpoch.equals(commandScopes.getFirst().expectedEpoch())) { + throw new IllegalArgumentException("Exact command source scope and epoch are required"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, CommandSource.APPLICATION_SCHEMA); + DraftAuthorizationFenceBinding.frame( + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, CommandSource.mutationsJson(mutations)); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String resultIdentity() { + return "command-source:" + binding.commitId() + ":" + CommandSource.sha256(canonicalBytes()); + } + + public AppliedEpoch commandAppliedEpoch() { + return new AppliedEpoch( + CommandSource.SCOPE, + binding.target().canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + private static boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void requireCounter(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("expectedEpoch must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java new file mode 100644 index 0000000000..a4085e12d4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective command set captured at one actual synchronized Draft commit. */ +public record CommandSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + String genesisReceiptDigest, + List definitions) { + public CommandSnapshot { + Objects.requireNonNull(binding, "binding"); + requireCounter(sourceEpoch, "sourceEpoch"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + if (genesisReceiptDigest == null || !genesisReceiptDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact command source genesis receipt digest required"); + } + definitions = List.copyOf(Objects.requireNonNull(definitions, "definitions")); + CommandSource.requireCanonicalDefinitions(definitions); + } + + @Override + public List definitions() { + return List.copyOf(definitions); + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + CommandSource.SNAPSHOT_SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptDigest", + genesisReceiptDigest, + "definitions", + CommandSource.tree(CommandSource.definitionsJson(definitions)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static CommandSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptDigest", + "definitions"); + if (!CommandSource.SNAPSHOT_SCHEMA.equals(CommandSource.requiredStoredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported command source snapshot schema"); + } + var inheritedNode = root.get("inheritedCommitId"); + if (inheritedNode == null || !inheritedNode.isTextual()) { + throw new IllegalArgumentException("Stored command source inheritedCommitId must be text"); + } + String inherited = inheritedNode.textValue(); + UUID inheritedCommitId = inherited.isEmpty() ? null : UUID.fromString(inherited); + if (inheritedCommitId != null && !inheritedCommitId.toString().equals(inherited)) { + throw new IllegalArgumentException( + "Stored command source inheritedCommitId must be a canonical UUID"); + } + var result = + new CommandSnapshot( + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")), + CommandSource.requiredStoredText(root, "sourceEpoch"), + inheritedCommitId, + CommandSource.requiredStoredText(root, "genesisReceiptDigest"), + CommandSource.definitionsFromStored(root.get("definitions").toString())); + if (!result.canonicalJson().equals(json)) { + throw new IllegalArgumentException( + "Stored command source snapshot is not exact canonical JSON"); + } + return result; + } + + /** Frozen source paired with the actual operation bytes and selected synchronized snapshot. */ + public record Capture(GameDesignPublicationOperation operation, CommandSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(snapshot, "snapshot"); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen command source differs from the exact selected synchronized commit"); + } + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-command-source-capture/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, operation.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java new file mode 100644 index 0000000000..40a0d14213 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -0,0 +1,645 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.command.CommandEffectDeclarationConstraints; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Typed complete effective source for Game Design's authored command definitions. */ +public final class CommandSource { + public static final String SCOPE = "COMMAND_DEFINITION_SET"; + public static final String SCOPE_ID = "effective"; + public static final String SNAPSHOT_SCHEMA = "game-design-command-source-snapshot/v1"; + public static final String APPLICATION_SCHEMA = "game-design-command-source-application/v1"; + public static final String REALM_POLICY_REVISION_KIND = "REALM_ENTRY_POLICY"; + + private static final String REVISION_KIND = "COMMAND_DEFINITION"; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0, 0); + private static final ObjectMapper JSON = new ObjectMapper(); + + private CommandSource() {} + + public enum OperationKind { + UPSERT, + DELETE + } + + /** One exact authored command definition with its creating revision and commit provenance. */ + public record Definition( + String commandId, + String definitionJson, + UUID sourceCommitId, + UUID sourceRevisionId, + String revisionOrder) { + public Definition { + requireText(commandId, "commandId"); + Objects.requireNonNull(definitionJson, "definitionJson"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + requireCounter(revisionOrder, "revisionOrder"); + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Command source key differs from the exact definition"); + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + } + + /** One explicit command mutation. DELETE retains identity and source revision provenance. */ + public record Mutation( + String revisionOrder, + UUID revisionId, + UUID commitId, + OperationKind operation, + String commandId, + String definitionJson) { + public Mutation { + requireCounter(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(operation, "operation"); + requireText(commandId, "commandId"); + if ((operation == OperationKind.UPSERT) != (definitionJson != null)) { + throw new IllegalArgumentException("Command mutation definition presence is invalid"); + } + if (definitionJson != null) { + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Upsert identity differs from its command definition"); + } + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + + public Map canonicalObject() { + Map value = new LinkedHashMap<>(); + value.put("revisionOrder", revisionOrder); + value.put("revisionId", revisionId.toString()); + value.put("commitId", commitId.toString()); + value.put("operation", operation.name()); + value.put("commandId", commandId); + if (definitionJson != null) value.put("definitionJson", definitionJson); + return value; + } + } + + /** Exact receipt supplied only by the owner path that inserted a genuinely new Draft Version. */ + public record NewDraftGenesisReceipt( + DraftCommitBinding.TargetProof target, UUID receiptId, String creationTransactionId) { + public NewDraftGenesisReceipt { + Objects.requireNonNull(target, "target"); + requireNonNil(receiptId, "receiptId"); + if (creationTransactionId == null || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Exact Version insertion transaction identity is required"); + } + } + + public String targetProofJson() { + return canonical(targetObject(target)); + } + + public byte[] canonicalBytes() { + return canonical( + Map.of( + "schema", + "game-design-command-source-new-draft-genesis/v1", + "targetProof", + tree(targetProofJson()), + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId)) + .getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return sha256(canonicalBytes()); + } + } + + /** + * Converts the closed Draft owner payloads to command mutations. Realm policy payloads are a + * separate Game Design owner scope and are deliberately left for their own source writer. Unknown + * kinds deny rather than being guessed from omitted or legacy rows. + */ + public static List mutations(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + List mutations = new ArrayList<>(); + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) continue; + if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + if (!payload.path("schemaVersion").isInt() + || payload.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command source operation schema"); + } + String operation = requiredText(payload, "operation"); + if ("UPSERT".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "definitionJson"); + String definitionJson = requiredText(payload, "definitionJson"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.UPSERT, + commandIdFrom(definitionJson), + definitionJson)); + } else if ("DELETE".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "commandId"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.DELETE, + requiredText(payload, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Unsupported command source operation"); + } + } + return List.copyOf(mutations); + } + + public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + boolean found = false; + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { + found = true; + } else if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + } + return found; + } + + /** Payload builder for a new immutable Draft binding; its result is part of binding.digest(). */ + public static String upsertPayload(String definitionJson) { + validateCommandDefinition(definitionJson); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "UPSERT", + "definitionJson", definitionJson)); + } + + /** + * Payload builder for an explicit digest-bound delete; absence is never interpreted as delete. + */ + public static String deletePayload(String commandId) { + requireText(commandId, "commandId"); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "DELETE", + "commandId", commandId)); + } + + public static List replay(List inherited, List mutations) { + Objects.requireNonNull(inherited, "inherited"); + Objects.requireNonNull(mutations, "mutations"); + Map effective = new HashMap<>(); + for (Definition definition : inherited) { + if (effective.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Inherited command source repeats a stable command key"); + } + } + String previousOrder = null; + UUID commitId = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : mutations) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || (commitId != null && !commitId.equals(mutation.commitId())) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Command mutations must retain one canonical commit and increasing revision order"); + } + previousOrder = mutation.revisionOrder(); + commitId = mutation.commitId(); + if (mutation.operation() == OperationKind.DELETE) { + effective.remove(mutation.stableKey()); + } else { + effective.put( + mutation.stableKey(), + new Definition( + mutation.commandId(), + mutation.definitionJson(), + mutation.commitId(), + mutation.revisionId(), + mutation.revisionOrder())); + } + } + List result = + effective.values().stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + validateDistinctCommandTokens(result); + return result; + } + + static String definitionsJson(List definitions) { + return canonical( + definitions.stream() + .sorted(Comparator.comparing(Definition::stableKey)) + .map(CommandSource::definitionObject) + .toList()); + } + + static List definitionsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) throw new IllegalArgumentException("Complete command array is required"); + List definitions = new ArrayList<>(); + for (JsonNode item : root) { + fields( + item, + "commandId", + "definitionJson", + "sourceCommitId", + "sourceRevisionId", + "revisionOrder"); + definitions.add( + new Definition( + requiredText(item, "commandId"), + requiredText(item, "definitionJson"), + UUID.fromString(requiredText(item, "sourceCommitId")), + UUID.fromString(requiredText(item, "sourceRevisionId")), + requiredText(item, "revisionOrder"))); + } + List result = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitionsJson(result).equals(json)) { + throw new IllegalArgumentException("Stored command source set is not canonical"); + } + validateDistinctCommandTokens(result); + return List.copyOf(result); + } + + static String mutationsJson(List mutations) { + return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); + } + + static List mutationsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) + throw new IllegalArgumentException("Complete command operation list is required"); + List result = new ArrayList<>(); + for (JsonNode item : root) { + String operation = requiredText(item, "operation"); + if ("UPSERT".equals(operation)) { + fields( + item, + "revisionOrder", + "revisionId", + "commitId", + "operation", + "commandId", + "definitionJson"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.UPSERT, + requiredText(item, "commandId"), + requiredText(item, "definitionJson"))); + } else if ("DELETE".equals(operation)) { + fields(item, "revisionOrder", "revisionId", "commitId", "operation", "commandId"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.DELETE, + requiredText(item, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Stored command operation kind is unsupported"); + } + } + String previousOrder = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : result) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Stored command operations are not in exact revision order"); + } + previousOrder = mutation.revisionOrder(); + } + return List.copyOf(result); + } + + static void requireCanonicalDefinitions(List definitions) { + List sorted = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitions.equals(sorted)) { + throw new IllegalArgumentException( + "Command source definitions are not in canonical stable-key order"); + } + Map unique = new HashMap<>(); + for (Definition definition : definitions) { + if (unique.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Command source repeats a stable command key"); + } + } + validateDistinctCommandTokens(definitions); + } + + static void requireStoredFields(JsonNode node, String... fields) { + CommandSource.fields(node, fields); + } + + static String requiredStoredText(JsonNode node, String field) { + return requiredText(node, field); + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical command source encoding failed", failure); + } + } + + static JsonNode tree(String json) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(json)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous command source JSON required", failure); + } + } + + static byte[] canonicalBytes(String json) { + return json.getBytes(StandardCharsets.UTF_8); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } + + static Map targetObject(DraftCommitBinding.TargetProof target) { + Map result = new LinkedHashMap<>(); + result.put("canonicalTenantId", target.canonicalTenantId().toString()); + result.put("canonicalVersionId", target.canonicalVersionId().toString()); + result.put("gameDesignVersionRowId", target.gameDesignVersionRowId()); + result.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + result.put("sourceGameRowId", target.sourceGameRowId()); + result.put("sourceGameTenantKey", target.sourceGameTenantKey()); + result.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return result; + } + + private static Map definitionObject(Definition definition) { + return Map.of( + "commandId", definition.commandId(), + "definitionJson", definition.definitionJson(), + "sourceCommitId", definition.sourceCommitId().toString(), + "sourceRevisionId", definition.sourceRevisionId().toString(), + "revisionOrder", definition.revisionOrder()); + } + + private static void validateDistinctCommandTokens(List definitions) { + Map tokenOwners = new HashMap<>(); + Map commandIds = new HashMap<>(); + for (Definition definition : definitions) { + String commandId = normalizeToken(definition.commandId()); + if (commandIds.putIfAbsent(commandId, Boolean.TRUE) != null) { + throw new IllegalArgumentException("Duplicate command definition id " + commandId); + } + ensureSingleTokenOwner(tokenOwners, commandId, commandId); + JsonNode aliases = tree(definition.definitionJson()).get("aliases"); + for (JsonNode alias : aliases) { + String normalized = normalizeToken(alias.asText()); + ensureSingleTokenOwner(tokenOwners, normalized, commandId); + } + } + } + + private static void ensureSingleTokenOwner( + Map owners, String token, String commandId) { + String existing = owners.putIfAbsent(token, commandId); + if (existing != null && !existing.equals(commandId)) { + throw new IllegalArgumentException("Ambiguous published command token " + token); + } + } + + private static String commandIdFrom(String definitionJson) { + validateCommandDefinition(definitionJson); + return requiredText(tree(definitionJson), "commandId"); + } + + /** Mirrors the currently accepted revision and release schema while preserving the raw JSON. */ + private static void validateCommandDefinition(String json) { + JsonNode definition = tree(json); + if (!definition.isObject() || definition.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command definition schema"); + } + requiredText(definition, "commandId"); + requiredText(definition, "semanticOwner"); + requireEnum(definition, "executionDiscipline", "DURABLE_GAMEPLAY"); + requireEnum(definition, "stageRequirement", "NONE", "LOGIN", "GAMEPLAY"); + requireEnum(definition, "promptPolicy", "NEVER", "WHEN_LOGGED_IN", "WHEN_GAMEPLAY"); + requireEnum(definition, "actionCategory", "GAMEPLAY", "SOCIAL", "META", "ADMIN", "SYSTEM"); + JsonNode history = definition.get("historyRecordable"); + if (history == null || !history.isBoolean()) { + throw new IllegalArgumentException("historyRecordable must be a boolean"); + } + requireTextArray(definition, "aliases"); + requireEnumArray( + definition, + "actionTags", + "MOVEMENT", + "COMMUNICATION", + "COMBAT", + "INVENTORY", + "WORLD_BROWSE", + "SOCIAL_PRESENCE", + "AUTHORING", + "SESSION", + "UI"); + JsonNode effects = definition.get("effects"); + if (effects == null || !effects.isArray()) { + throw new IllegalArgumentException("effects must be an array"); + } + for (JsonNode effect : effects) validateEffect(effect); + } + + private static void validateEffect(JsonNode effect) { + if (!effect.isObject() + || !"APPLY_ACTION_STATE".equals(requiredText(effect, "effectKind")) + || !effect.path("schemaVersion").isInt() + || effect.path("schemaVersion").asInt() != 1 + || !"SELF".equals(requiredText(effect, "targeting")) + || !"EFFECT_IDEMPOTENT".equals(requiredText(effect, "replayPolicy"))) { + throw new IllegalArgumentException("Unsupported command effect declaration"); + } + JsonNode payload = effect.get("payload"); + if (payload == null || !payload.isObject()) + throw new IllegalArgumentException("Effect payload must be an object"); + requireIdentifier(payload, "conditionKey"); + JsonNode duration = payload.get("durationSeconds"); + if (duration == null + || !duration.isInt() + || !CommandEffectDeclarationConstraints.isValidDurationSeconds(duration.asInt())) { + throw new IllegalArgumentException("Command action-state duration is unsupported"); + } + JsonNode effectPayload = payload.get("effectPayload"); + JsonNode modifiers = effectPayload == null ? null : effectPayload.get("modifiers"); + if (effectPayload == null + || !effectPayload.isObject() + || modifiers == null + || !modifiers.isArray()) { + throw new IllegalArgumentException("Command effect modifiers must be an array"); + } + for (JsonNode modifier : modifiers) { + if (!modifier.isObject()) + throw new IllegalArgumentException("Command effect modifier must be an object"); + String operation = requiredText(modifier, "operation"); + if (!CommandEffectDeclarationConstraints.SUPPORTED_MODIFIER_OPERATIONS.contains(operation)) { + throw new IllegalArgumentException("Unsupported command effect modifier operation"); + } + requireIdentifier(modifier, "target_key"); + JsonNode value = modifier.get("value"); + if (value == null || !value.isNumber()) + throw new IllegalArgumentException("Command effect modifier value must be numeric"); + optionalIdentifier(modifier, "scope_kind"); + optionalIdentifier(modifier, "scope_key"); + JsonNode priority = modifier.get("priority"); + if (priority != null && !priority.isInt()) + throw new IllegalArgumentException("Command effect priority must be an integer"); + } + } + + private static void requireIdentifier(JsonNode source, String field) { + String value = requiredText(source, field); + if (!CommandEffectDeclarationConstraints.isIdentifier(value)) { + throw new IllegalArgumentException("Command effect identifier is invalid: " + field); + } + } + + private static void optionalIdentifier(JsonNode source, String field) { + if (source.get(field) != null) requireIdentifier(source, field); + } + + private static void requireEnum(JsonNode source, String field, String... allowed) { + String actual = requiredText(source, field); + for (String value : allowed) if (value.equals(actual)) return; + throw new IllegalArgumentException("Unsupported command definition field " + field); + } + + private static void requireEnumArray(JsonNode source, String field, String... allowed) { + requireTextArray(source, field); + List supported = List.of(allowed); + for (JsonNode item : source.get(field)) { + if (!supported.contains(item.asText())) { + throw new IllegalArgumentException("Unsupported command definition value in " + field); + } + } + } + + private static void requireTextArray(JsonNode source, String field) { + JsonNode values = source.get(field); + if (values == null || !values.isArray()) { + throw new IllegalArgumentException("Command definition array is required: " + field); + } + for (JsonNode value : values) { + if (!value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException( + "Command definition array has an invalid entry: " + field); + } + } + } + + private static String requiredText(JsonNode source, String field) { + JsonNode value = source.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException("Command definition text is required: " + field); + } + return value.asText(); + } + + private static String normalizeToken(String token) { + if (token == null || token.isBlank()) { + throw new IllegalArgumentException("Command token must not be blank"); + } + return token.trim().toLowerCase(Locale.ROOT); + } + + private static void fields(JsonNode node, String... names) { + if (!node.isObject() || node.size() != names.length) { + throw new IllegalArgumentException("Closed command source operation fields are required"); + } + for (String name : names) { + if (node.get(name) == null) + throw new IllegalArgumentException("Missing command source field " + name); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank() || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException(name + " must be nonblank valid UTF-8 text"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) + throw new IllegalArgumentException(name + " must be non-nil"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java new file mode 100644 index 0000000000..ffc60d15a4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -0,0 +1,809 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage for a complete effective command set. Writes require the caller's + * coordinator transaction; this repository does not register an owner outcome or authorize a + * publication. + */ +public final class CommandSourceRepository { + private final DSLContext dsl; + + public CommandSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Explicit empty genesis for a Version known by its creation owner to be newly inserted as a + * Draft. Call only in that exact Version insertion transaction. Missing source rows alone never + * establish genesis, and this receipt is not a Draft commit. + */ + public CommandSource.NewDraftGenesisReceipt enrollNewDraftGenesis( + CommandSource.NewDraftGenesisReceipt receipt) { + requireWrite(); + Objects.requireNonNull(receipt, "receipt"); + TargetProof target = receipt.target(); + lockAuthority(target); + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || !Long.valueOf(1L).equals(version.get("version_state_epoch", Long.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_REQUIRES_NEW_FULL_DRAFT_EPOCH_ONE"); + } + Optional existing = baseline(target); + if (existing.isPresent()) { + Record row = existing.orElseThrow(); + if (!Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class)) + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !receipt.receiptId().equals(row.get("receipt_id", UUID.class)) + || !receipt + .creationTransactionId() + .equals(row.get("creation_transaction_id", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), true); + if (head(target).isPresent() + || new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).isPresent()) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_AFTER_DRAFT_COMMIT_DENIED"); + } + dsl.execute( + "INSERT INTO game_design_command_source_baseline " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, baseline_kind, " + + "receipt_id, creation_transaction_id, target_proof_json, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, 'NEW_DRAFT_EMPTY', ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + receipt.receiptId(), + receipt.creationTransactionId(), + receipt.targetProofJson(), + receipt.canonicalBytes(), + receipt.digest()); + dsl.execute( + "INSERT INTO game_design_command_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, applied_commit_id, baseline_digest) " + + "VALUES (?, ?, '0', NULL, NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.digest()); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + + /** Exact readback of an explicitly enrolled empty new-Draft baseline; absence stays absent. */ + public Optional readNewDraftGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + Optional stored = baseline(target); + if (stored.isEmpty()) return Optional.empty(); + Record row = stored.orElseThrow(); + CommandSource.NewDraftGenesisReceipt receipt = + new CommandSource.NewDraftGenesisReceipt( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (row.get("game_design_version_row_id", Long.class) != target.gameDesignVersionRowId() + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_READBACK_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + return Optional.of(receipt); + } + + /** + * Applies command operations to private staged source. The returned evidence is one component of + * GAME_DESIGN_CONTROL_PLANE's combined APPLIED result; this method never records that result. + */ + public Optional apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + List mutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteControlPlaneScopes(binding, mutations, policyMutation); + Optional existing = application(binding); + if (existing.isPresent()) return existing; + if (mutations.isEmpty()) return Optional.empty(); + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireCoordinatorApplicationSlot(binding); + requireOwnerApplyStarted(binding); + + Record head = requireHead(target); + String expectedEpoch = commandScope(binding).expectedEpoch(); + if (!expectedEpoch.equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + } + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + requireVisibleHeadMatchesFence(target, inheritedCommitId); + String baselineDigest = head.get("baseline_digest", String.class); + List inheritedDefinitions; + if (inheritedCommitId == null) { + inheritedDefinitions = List.of(); + if (!"0".equals(expectedEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(expectedEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + inheritedDefinitions = inherited.definitions(); + } + for (CommandSource.Mutation mutation : mutations) + requireRevisionIdentityUnused(target, mutation); + String resultEpoch = new BigInteger(expectedEpoch).add(BigInteger.ONE).toString(); + CommandSnapshot snapshot = + new CommandSnapshot( + binding, + resultEpoch, + inheritedCommitId, + baselineDigest, + CommandSource.replay(inheritedDefinitions, mutations)); + CommandApplication result = + new CommandApplication(binding, inheritedCommitId, expectedEpoch, mutations, snapshot); + insertApplication(result, baselineDigest); + insertOperations(result); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM ?", + resultEpoch, + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + expectedEpoch, + inheritedCommitId); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + return Optional.of( + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_READBACK_FAILED"))); + } + + /** + * Makes the staged complete source visible only after the coordinator's exact synchronized fence + * and combined owner outcome are durable in this same transaction. + */ + public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + Optional existing = readSnapshot(target, binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + return existing.orElseThrow(); + } + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireExactSynchronizedOwnerResult(binding); + Record head = requireHead(target); + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + String baselineDigest = head.get("baseline_digest", String.class); + String sourceEpoch = head.get("source_epoch", String.class); + List mutations = CommandSource.mutations(binding); + requireCompleteControlPlaneScopes( + binding, mutations, CommandSource.hasRealmPolicyRevision(binding)); + List definitions; + if (!mutations.isEmpty()) { + CommandApplication applied = + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_UNAVAILABLE")); + if (!applied.snapshot().sourceEpoch().equals(sourceEpoch) + || !applied.snapshot().genesisReceiptDigest().equals(baselineDigest) + || !Objects.equals(applied.inheritedCommitId(), inheritedCommitId)) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_NOT_CURRENT"); + } + definitions = applied.snapshot().definitions(); + } else if (inheritedCommitId == null) { + if (!"0".equals(sourceEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + definitions = List.of(); + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(sourceEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + definitions = inherited.definitions(); + } + CommandSnapshot snapshot = + new CommandSnapshot(binding, sourceEpoch, inheritedCommitId, baselineDigest, definitions); + dsl.execute( + "INSERT INTO game_design_command_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, source_epoch, snapshot_json, snapshot_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + inheritedCommitId, + baselineDigest, + sourceEpoch, + snapshot.canonicalJson(), + snapshot.digest()); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET visible_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM ? AND source_epoch = ?", + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + inheritedCommitId, + sourceEpoch); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CONFLICT"); + return readSnapshot(target, binding.commitId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_READBACK_FAILED")); + } + + /** Captures source against the actual original publication operation and exact selected fence. */ + public CommandSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + lockAuthority(target); + Optional existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireOpenDraft(target); + Record selected = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selected == null + || !selection.canonicalJson().equals(selected.get("selection_json", String.class)) + || !selection.digest().equals(selected.get("selection_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_UNAVAILABLE"); + } + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow( + () -> + new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_UNAVAILABLE")); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_SEALED"); + } + Record versionRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()), + "COMMAND_SOURCE_VERSION_UNAVAILABLE"); + Long versionEpoch = versionRow.get("version_state_epoch", Long.class); + if (versionEpoch == null + || !selection.intent().expectedVersionStateEpoch().equals(Long.toString(versionEpoch))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_VERSION_EPOCH_CHANGED"); + } + DraftCommitBinding selectedCommit = selection.selectedCommit(); + requireCurrentFence(selectedCommit); + CommandSnapshot snapshot = + readSnapshot(target, selectedCommit.commitId()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SELECTED_SNAPSHOT_UNAVAILABLE")); + Record head = requireHead(target); + if (!selectedCommit.equals(snapshot.binding()) + || !selectedCommit.commitId().equals(head.get("visible_commit_id", UUID.class)) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_SOURCE_NOT_SYNCHRONIZED"); + } + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_command_source_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, " + + "operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + selectedCommit.commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_READBACK_FAILED")); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_snapshot WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.binding().digest().equals(row.get("input_digest", String.class)) + || !snapshot.binding().canonicalJson().equals(row.get("binding_json", String.class)) + || !snapshot.sourceEpoch().equals(row.get("source_epoch", String.class)) + || !snapshot.genesisReceiptDigest().equals(row.get("baseline_digest", String.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_STORAGE_CONFLICT"); + } + var commit = + new DraftCommitCoordinatorRepository(dsl) + .read(target, snapshot.binding().requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + Record fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (!commit.binding().equals(snapshot.binding()) + || fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyDefinitionProvenance(snapshot); + return Optional.of(snapshot); + } + + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !selection.selectedCommit().commitId().equals(row.get("commit_id", UUID.class))) { + throw new IllegalArgumentException("COMMAND_SOURCE_FREEZE_OPERATION_CONFLICT"); + } + CommandSnapshot snapshot = + readSnapshot(target, row.get("commit_id", UUID.class)) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_SNAPSHOT_UNAVAILABLE")); + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + private void insertApplication(CommandApplication application, String baselineDigest) { + DraftCommitBinding binding = application.binding(); + dsl.execute( + "INSERT INTO game_design_command_source_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, expected_epoch, snapshot_json, " + + "operations_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + application.inheritedCommitId(), + baselineDigest, + application.expectedEpoch(), + application.snapshot().canonicalJson(), + CommandSource.mutationsJson(application.mutations()), + application.canonicalBytes()); + } + + private void insertOperations(CommandApplication application) { + for (CommandSource.Mutation mutation : application.mutations()) { + String operationJson = CommandSource.canonical(mutation.canonicalObject()); + dsl.execute( + "INSERT INTO game_design_command_source_operation " + + "(canonical_tenant_id, canonical_version_id, commit_id, revision_order, revision_id, " + + "operation_kind, command_id, command_key, definition_json, operation_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + application.binding().target().canonicalTenantId(), + application.binding().target().canonicalVersionId(), + application.binding().commitId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.revisionId(), + mutation.operation().name(), + mutation.commandId(), + mutation.stableKey(), + mutation.definitionJson(), + operationJson); + } + } + + private Optional application(DraftCommitBinding binding) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_application WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + DraftCommitBinding stored = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + String operationsJson = row.get("operations_json", String.class); + List mutations = CommandSource.mutationsFromStored(operationsJson); + CommandApplication result = + new CommandApplication( + stored, + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + mutations, + snapshot); + if (!stored.equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !CommandSource.mutationsJson(mutations).equals(operationsJson) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_EXACT_BINDING_CONFLICT"); + } + List storedOperations = + dsl.fetch( + "SELECT operation_json FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("operation_json", String.class); + if (!storedOperations.equals( + result.mutations().stream() + .map(m -> CommandSource.canonical(m.canonicalObject())) + .toList())) { + throw new IllegalStateException("COMMAND_SOURCE_OPERATION_READBACK_CONFLICT"); + } + return Optional.of(result); + } + + private void verifyDefinitionProvenance(CommandSnapshot snapshot) { + for (CommandSource.Definition definition : snapshot.definitions()) { + Record row = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + definition.sourceCommitId()); + if (row == null) + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_COMMIT_UNAVAILABLE"); + DraftCommitBinding original = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!original.target().equals(snapshot.binding().target())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_TARGET_CHANGED"); + } + CommandSource.Mutation source = + CommandSource.mutations(original).stream() + .filter(mutation -> mutation.revisionId().equals(definition.sourceRevisionId())) + .filter(mutation -> mutation.operation() == CommandSource.OperationKind.UPSERT) + .findFirst() + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_AUTHORED_REVISION_UNAVAILABLE")); + if (!source.commandId().equals(definition.commandId()) + || !source.definitionJson().equals(definition.definitionJson()) + || !source.commitId().equals(definition.sourceCommitId())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_PROVENANCE_CHANGED"); + } + } + } + + private void requireCompleteControlPlaneScopes( + DraftCommitBinding binding, + List commandMutations, + boolean policyMutation) { + List units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream().filter(this::isCommandScope).toList(); + List policies = + units.stream().filter(this::isPolicyScope).toList(); + if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) + || policies.size() != (policyMutation ? 1 : 0) + || commands.size() + policies.size() != units.size()) { + throw new IllegalArgumentException( + "Complete supported Game Design control-plane scopes are required"); + } + if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); + if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); + } + + private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private boolean isPolicyScope(DraftCommitBinding.AffectedUnit unit) { + return RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId()); + } + + private void requireScopeTarget(DraftCommitBinding.AffectedUnit unit, TargetProof target) { + if (!target.canonicalVersionId().toString().equals(unit.aggregateId())) { + throw new IllegalArgumentException( + "Control-plane scope must bind the exact canonical Version"); + } + } + + private DraftCommitBinding.AffectedUnit commandScope(DraftCommitBinding binding) { + return binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(this::isCommandScope) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("Command source affected scope is omitted")); + } + + private void requireCoordinatorApplicationSlot(DraftCommitBinding binding) { + var slot = + new DraftCommitCoordinatorRepository(dsl) + .readApplicationSlot(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_CHANGED"); + } + } + + private void requireOwnerApplyStarted(DraftCommitBinding binding) { + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != OwnerStatus.IN_PROGRESS && state.status() != OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("COMMAND_SOURCE_OWNER_APPLICATION_NOT_STARTED"); + } + } + + private void requireExactSynchronizedOwnerResult(DraftCommitBinding binding) { + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + var commit = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + var owner = commit.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!commit.binding().equals(binding) + || commit.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED + || !binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + if (binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE) + && (owner == null + || owner.status() != OwnerStatus.APPLIED + || owner.outcome().isEmpty() + || !binding.commitId().equals(owner.outcome().orElseThrow().commitId()) + || !binding.digest().equals(owner.outcome().orElseThrow().bindingDigest()))) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + } + + private void requireVisibleHeadMatchesFence(TargetProof target, UUID visibleCommitId) { + var fence = new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target); + if (visibleCommitId == null) { + if (fence.isPresent()) + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } else if (fence.isEmpty() || !visibleCommitId.equals(fence.orElseThrow().commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } + } + + private void requireCurrentFence(DraftCommitBinding binding) { + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE")); + if (!binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_COMMIT_NOT_CURRENT"); + } + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + if (!retained.binding().equals(binding)) { + throw new IllegalArgumentException("COMMAND_SOURCE_COMMIT_BINDING_CONFLICT"); + } + } + + private void requireRevisionIdentityUnused(TargetProof target, CommandSource.Mutation mutation) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + mutation.revisionId()) + != null) { + throw new IllegalArgumentException("COMMAND_SOURCE_REVISION_ID_REUSE"); + } + } + + private Optional baseline(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_baseline WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Optional head(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Record requireHead(TargetProof target) { + return head(target) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_BASELINE_UNAVAILABLE")); + } + + private void requireHeadBaseline(TargetProof target, String digest) { + Record row = requireHead(target); + if (!digest.equals(row.get("baseline_digest", String.class)) + || !"0".equals(row.get("source_epoch", String.class)) + || row.get("visible_commit_id", UUID.class) != null + || row.get("applied_commit_id", UUID.class) != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_READBACK_CONFLICT"); + } + } + + private void requireVersionInsertWitness( + TargetProof target, String creationTransactionId, boolean requireCurrentTransaction) { + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ?", + target.gameDesignVersionRowId()); + Record currentTransaction = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_current_xact_id()::TEXT AS transaction_id"), + "COMMAND_SOURCE_CURRENT_TRANSACTION_UNAVAILABLE"); + String currentTransactionId = currentTransaction.get("transaction_id", String.class); + if (witness == null + || !creationTransactionId.equals(witness.get("creation_transaction_id", String.class)) + || (requireCurrentTransaction && !creationTransactionId.equals(currentTransactionId))) { + throw new IllegalStateException("COMMAND_SOURCE_NEW_DRAFT_INSERTION_WITNESS_UNAVAILABLE"); + } + } + + private void requireOpenDraft(TargetProof target) { + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_RESERVED"); + } + } + + private void lockAuthority(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + } + + private Record version(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.id, v.tenant_id, v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, v.identity_source_provenance_kind, " + + "v.version_state, v.version_state_epoch, v.is_script_only, v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ?", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + return row; + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Command source writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java new file mode 100644 index 0000000000..45d095299a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.gamedesign.publication; + +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed original operation input. Codec validation supplies integrity, never authorization. */ +public record GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; + + public GameDesignPublicationOperation { + var binding = new GameDesignPublicationOperationBinding(account, world); + account = binding.account(); + world = binding.world(); + } + + public byte[] canonicalBytes() { + return new GameDesignPublicationOperationBinding(account, world).canonicalBytes(); + } + + public static GameDesignPublicationOperation fromStored(byte[] bytes) { + var binding = GameDesignPublicationOperationBinding.fromStored(bytes); + return new GameDesignPublicationOperation(binding.account(), binding.world()); + } + + public String workflowId() { + return world.request().publishWorkflowId(); + } + + public String tenantKey() { + return account.input().selection().target().gameDesignVersionTenantKey(); + } + + public long versionId() { + return account.input().selection().target().gameDesignVersionRowId(); + } + + public String selectionDigest() { + return account.input().selection().digest(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java new file mode 100644 index 0000000000..0714337e59 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -0,0 +1,254 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner storage only. Deliberately has no runtime bean or authenticated ingress. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class GameDesignPublicationOperationRepository { + private final DSLContext dsl; + + public GameDesignPublicationOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public void reserve(GameDesignPublicationOperation operation) { + requireTransaction(); + lock(operation.tenantKey(), operation.workflowId(), operation.versionId()); + Optional existing = read(operation.workflowId()); + if (existing.isPresent()) { + exact(existing.get().operation(), operation); + return; + } + dsl.execute( + "INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), + operation.tenantKey(), + operation.versionId(), + operation.selectionDigest(), + operation.canonicalBytes()); + } + + /** Caller has already proved authorization; reservation and source freeze are one transaction. */ + public GameDesignSourceRepository.Capture reserveSourceBacked( + GameDesignPublicationOperation operation) { + reserve(operation); + return new GameDesignSourceRepository(dsl).freeze(operation); + } + + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return new GameDesignSourceRepository(dsl).readCapture(operation); + } + + public GameDesignPublicationOperation requirePending( + String tenant, String workflow, long version, String digest) { + requireTransaction(); + lock(tenant, workflow, version); + Readback result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !result.outcome().equals("PENDING")) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + return operation; + } + + public void seal(String tenant, String workflow, long version, String digest, boolean published) { + GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); + Record release = + dsl.fetchOne( + "SELECT r.*, to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + tenant, + version); + String evidence = release == null ? null : release.get("evidence", String.class); + if (published != (evidence != null)) + throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); + String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; + byte[] result = receipt(operation, outcome, evidence); + Long publicationEpoch = null; + if (published) { + Record committedVersion = + dsl.fetchOne( + "SELECT version_state, version_state_epoch FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenant, + version); + if (committedVersion == null + || !"PUBLISHED".equals(committedVersion.get("version_state", String.class))) { + throw new IllegalStateException("PUBLICATION_VERSION_NOT_COMMITTED"); + } + publicationEpoch = committedVersion.get("version_state_epoch", Long.class); + } + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.valueOf(outcome), + published ? PublicationReleaseContent.fromRow(release) : null, + publicationEpoch); + int changed = + dsl.execute( + "UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", + outcome, + result, + evidence, + terminal.canonicalBytes(), + publicationEpoch, + published ? terminal.releaseContent().canonicalBytes() : null, + published ? terminal.publishedReleaseBundleDigest() : null, + workflow); + if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); + } + + public Optional read(String workflow) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", + workflow); + if (row == null) return Optional.empty(); + var operation = + GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); + String outcome = row.get("outcome", String.class); + byte[] bytes = row.get("result_bytes", byte[].class); + String evidence = row.get("release_row_json", String.class); + byte[] terminalBytes = row.get("terminal_evidence_bytes", byte[].class); + if (!operation.workflowId().equals(workflow) + || !operation.tenantKey().equals(row.get("tenant_id", String.class)) + || operation.versionId() != row.get("version_id", Long.class) + || !operation.selectionDigest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_OPERATION_STORAGE_CONFLICT"); + } + if (!"PENDING".equals(outcome)) { + if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) + throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); + Record release = + dsl.fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + String actual = release == null ? null : release.get("evidence", String.class); + if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { + throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); + } + // V50 history remains readable but never acquires unverifiable forward evidence. + if (terminalBytes != null) { + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || !terminal.outcome().name().equals(outcome)) { + throw new IllegalStateException("PUBLICATION_TERMINAL_IDENTITY_CONFLICT"); + } + if (terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED) { + Record immutableRelease = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), + PublicationReleaseContent.fromRow(immutableRelease).canonicalBytes()) + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), + row.get("release_content_bytes", byte[].class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !terminal + .publishedReleaseBundleDigest() + .equals(row.get("published_release_bundle_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_TERMINAL_BACKING_CONFLICT"); + } + } + } + Record attempt = + dsl.fetchOne( + "SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); + if (attempt == null) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + String attemptStatus = attempt.get("status", String.class); + if (!("PUBLISHED".equals(outcome) ? "SUCCEEDED" : "FAILED").equals(attemptStatus)) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + } + return Optional.of(new Readback(operation, outcome, bytes, terminalBytes)); + } + + private void lock(String tenant, String workflow, long version) { + if (dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", tenant) == null + || dsl.fetchOne( + "SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", + tenant, + workflow, + version) + == null + || dsl.fetchOne( + "SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) + == null) { + throw new IllegalStateException("PUBLICATION_OWNER_IDENTITY_UNAVAILABLE"); + } + } + + public static void exact( + GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { + if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + + private static byte[] receipt( + GameDesignPublicationOperation operation, String outcome, String evidence) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + if (evidence == null) { + DraftAuthorizationFenceBinding.frame(out, new byte[0]); + } else { + DraftAuthorizationFenceBinding.frame(out, evidence); + } + return out.toByteArray(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Publication owner transaction required"); + } + + public record Readback( + GameDesignPublicationOperation operation, + String outcome, + byte[] receiptBytes, + byte[] terminalEvidenceBytes) { + public Readback { + receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); + terminalEvidenceBytes = terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + public Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + this(operation, outcome, receiptBytes, null); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + @Override + public byte[] receiptBytes() { + return receiptBytes == null ? null : receiptBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java new file mode 100644 index 0000000000..f0a5f87a14 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit local seam; upstream authentication/current authority must be established separately. + */ +public final class GameDesignPublicationOperationService { + private final GameDesignPublicationOperationRepository repository; + private final TransactionTemplate write; + private final TransactionTemplate read; + + public GameDesignPublicationOperationService( + GameDesignPublicationOperationRepository repository, + PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + write = new TransactionTemplate(transactions); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation( + GameDesignPublicationOperation operation) { + requireIndependent(); + var retained = readExact(operation); + if (retained.isPresent()) { + var original = retained.orElseThrow(); + if ("PENDING".equals(original.outcome())) { + read.executeWithoutResult( + status -> + repository + .readSourceCapture(operation) + .orElseThrow( + () -> new IllegalStateException("PUBLICATION_SOURCE_CAPTURE_UNAVAILABLE"))); + } + return original; + } + write.executeWithoutResult(status -> repository.reserveSourceBacked(operation)); + return readExact(operation) + .orElseThrow(() -> new IllegalStateException("Publication operation readback absent")); + } + + public Optional readExact( + GameDesignPublicationOperation operation) { + requireIndependent(); + return read.execute( + status -> + repository + .read(operation.workflowId()) + .map( + result -> { + GameDesignPublicationOperationRepository.exact(result.operation(), operation); + return result; + })); + } + + private static void requireIndependent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Independent publication read/write boundary required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..fa1b8ba391 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Standalone authenticated read adapter. Deliberately has no runtime registration. */ +public final class GameDesignPublicationTerminalReadGrpcService + extends GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase { + private final GameDesignPublicationOperationService owner; + private final String namespace; + + public GameDesignPublicationTerminalReadGrpcService( + GameDesignPublicationOperationService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readGameDesignPublicationTerminal( + ReadGameDesignPublicationTerminalRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (peer == null + || !(peer.uri().equals(prefix + "account-service") + || peer.uri().equals(prefix + "world-management-service")) + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Account or World workload without end-user context required"); + return; + } + final ReadRequest request; + try { + request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail( + observer, + Status.INVALID_ARGUMENT, + "Complete canonical publication terminal read request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail( + observer, + Status.PERMISSION_DENIED, + "Terminal read namespace differs from authenticated peer"); + return; + } + final ReadResult result; + try { + var operation = GameDesignPublicationOperation.fromStored(request.operationBytes()); + // readExact owns the independent read-only REPEATABLE_READ transaction and exact binding. + var stored = owner.readExact(operation); + if (stored.isEmpty() || stored.orElseThrow().outcome().equals("PENDING")) { + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()); + } else { + byte[] bytes = stored.orElseThrow().terminalEvidenceBytes(); + if (bytes == null) + throw new IllegalStateException("Historical terminal result has no captured evidence"); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(bytes); + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.valueOf( + stored.orElseThrow().outcome()), + Optional.of(terminal)); + } + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "Publication terminal owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException conflict) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Retained publication terminal evidence unavailable or inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Publication terminal owner read failed"); + return; + } + observer.onNext(GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result)); + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java new file mode 100644 index 0000000000..1281cca507 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseEvidence; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Joins the two actual Game Design sources under one caller-owned coordinator transaction. */ +public final class GameDesignSourceRepository { + private final DSLContext dsl; + private final RealmPolicySourceRepository policies; + private final CommandSourceRepository commands; + private final DraftCommitCoordinatorRepository coordinator; + + public GameDesignSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + policies = new RealmPolicySourceRepository(dsl); + commands = new CommandSourceRepository(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + /** + * Claim the exact reviewed proposal against actual owner evidence before any source dispatch. + * Account authorization and current permission through commit remain caller obligations. + */ + public DraftCommitCoordinatorRepository.CommitSnapshot claimReviewed( + DraftCommitBinding binding, GameDesignReviewedBaseEvidence reviewedEvidence) { + requireWrite(); + return new GameDesignReviewedBaseRepository(dsl).claimReviewed(binding, reviewedEvidence); + } + + /** Call only on the actual new full-Draft Version insertion branch, in that transaction. */ + public Genesis enrollFreshDraft(TargetProof target) { + requireWrite(); + Objects.requireNonNull(target, "target"); + RealmPolicyGenesis policy = policies.recordFreshGenesis(target); + CommandSource.NewDraftGenesisReceipt command = + commands.enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + target, policy.receiptId(), policy.creationTransactionId())); + Genesis result = new Genesis(policy, command); + if (!result.equals( + readGenesis(target) + .orElseThrow( + () -> + new IllegalStateException( + "GAME_DESIGN_SOURCE_GENESIS_READBACK_UNAVAILABLE")))) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_READBACK_CONFLICT"); + } + return result; + } + + public Optional readGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + var policy = policies.readGenesis(target); + var command = commands.readNewDraftGenesis(target); + if (policy.isEmpty() && command.isEmpty()) return Optional.empty(); + if (policy.isEmpty() || command.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + return Optional.of(new Genesis(policy.orElseThrow(), command.orElseThrow())); + } + + /** Stage actual source writes and record exactly one complete local owner outcome. */ + public Application apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + List commandMutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation); + requireGenesis(binding.target()); + requireReviewed(binding); + Optional command = commands.apply(binding); + if (command.isPresent() != !commandMutations.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_COMMAND_APPLICATION_INCOMPLETE"); + } + Optional policy = Optional.empty(); + if (policyMutation) { + // The policy-only path retains its existing exact owner result. Mixed input stages policy + // first, then records the combined result using the command store's actual readback bytes. + policy = + Optional.of( + command.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); + } + OwnerOutcome expected; + if (policy.isPresent() && command.isPresent()) { + var policyResult = policy.orElseThrow(); + var commandResult = command.orElseThrow(); + List epochs = + List.of( + commandResult.commandAppliedEpoch(), + policyResult.ownerOutcome().appliedEpochs().getFirst()); + policies.recordCombinedOwnerOutcome(binding, commandResult.canonicalBytes(), epochs); + expected = policyResult.combinedOwnerOutcome(commandResult.canonicalBytes(), epochs); + } else if (policy.isPresent()) { + expected = policy.orElseThrow().ownerOutcome(); + } else { + CommandApplication commandResult = command.orElseThrow(); + expected = commandOnlyOutcome(binding, commandResult); + coordinator.recordOwnerOutcome(binding, expected); + } + OwnerOutcome retained = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("GAME_DESIGN_COMMIT_READBACK_UNAVAILABLE")) + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome() + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_UNAVAILABLE")); + if (!expected.equals(retained)) { + throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); + } + return new Application(binding, command, policy, retained); + } + + /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ + public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + requireGenesis(binding.target()); + requireReviewed(binding); + CommandSnapshot command = commands.captureSynchronized(binding); + RealmPolicySnapshot policy = policies.captureSynchronized(binding); + if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); + } + return new SynchronizedSources(command, policy); + } + + /** Freeze both complete, selected source snapshots against the same retained operation. */ + public Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + requireGenesis(operation.account().input().selection().target()); + requireReviewed(operation.account().input().selection().selectedCommit()); + RealmPolicySnapshot.Capture policy = policies.freeze(operation); + CommandSnapshot.Capture command = commands.freeze(operation); + Capture result = new Capture(command, policy); + Capture retained = + readCapture(operation) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_UNAVAILABLE")); + if (!Arrays.equals(result.command().canonicalBytes(), retained.command().canonicalBytes()) + || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); + } + return retained; + } + + /** Exact stored captures for a bundle producer; partial capture cannot authorize publication. */ + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + requireReviewed(operation.account().input().selection().selectedCommit()); + var command = commands.readCapture(operation); + var policy = policies.readCapture(operation); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); + } + return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow())); + } + + public Optional readSynchronized(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + var command = commands.readSnapshot(target, commitId); + var policy = policies.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); + } + return Optional.of(new SynchronizedSources(command.orElseThrow(), policy.orElseThrow())); + } + + private void requireGenesis(TargetProof target) { + if (readGenesis(target).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + } + + private void requireReviewed(DraftCommitBinding binding) { + new GameDesignReviewedBaseRepository(dsl).requireRetained(binding); + } + + private static OwnerOutcome commandOnlyOutcome( + DraftCommitBinding binding, CommandApplication command) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-command-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, command.canonicalBytes()); + return new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + command.resultIdentity(), + out.toByteArray(), + List.of(command.commandAppliedEpoch())); + } + + private static void requireCompleteScopes( + DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy) { + if (!hasCommand && !hasPolicy + || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { + throw new IllegalArgumentException("Game Design owner requires typed source revisions"); + } + List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream() + .filter( + unit -> + CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId())) + .toList(); + List policies = + units.stream() + .filter( + unit -> + RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId())) + .toList(); + if (commands.size() != (hasCommand ? 1 : 0) + || policies.size() != (hasPolicy ? 1 : 0) + || commands.size() + policies.size() != units.size() + || units.stream() + .anyMatch( + unit -> + !binding.target().canonicalVersionId().toString().equals(unit.aggregateId()))) { + throw new IllegalArgumentException("Complete supported Game Design source scopes required"); + } + if (hasPolicy) { + binding.revisions().stream() + .filter(revision -> revision.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .forEach(revision -> RealmPolicySource.revision(binding, revision)); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Game Design source writes require caller-owned writable READ_COMMITTED transaction"); + } + } + + public record Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + public Genesis { + Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(command, "command"); + if (!policy.target().equals(command.target()) + || !policy.receiptId().equals(command.receiptId()) + || !policy.creationTransactionId().equals(command.creationTransactionId())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); + } + } + } + + public record Application( + DraftCommitBinding binding, + Optional command, + Optional policy, + OwnerOutcome ownerOutcome) { + public Application { + Objects.requireNonNull(binding, "binding"); + command = Objects.requireNonNull(command, "command"); + policy = Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(ownerOutcome, "ownerOutcome"); + if (command.isEmpty() && policy.isEmpty() + || command.isPresent() && !binding.equals(command.orElseThrow().binding()) + || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) + || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE + || ownerOutcome.status() != OwnerStatus.APPLIED + || !binding.commitId().equals(ownerOutcome.commitId()) + || !binding.digest().equals(ownerOutcome.bindingDigest())) { + throw new IllegalArgumentException("Owner application differs from exact Draft binding"); + } + } + } + + public record SynchronizedSources(CommandSnapshot command, RealmPolicySnapshot policy) { + public SynchronizedSources { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!command.binding().equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + } + } + + public record Capture(CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy) { + public Capture { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) + || !command.snapshot().binding().equals(policy.snapshot().binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); + } + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java new file mode 100644 index 0000000000..e330e02684 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; + +/** Maps the actual immutable release row, never a launch descriptor or a mutable Version read. */ +final class PublicationReleaseContent { + private PublicationReleaseContent() {} + + static GameDesignPublicationTerminalEvidence.ReleaseContent fromRow(Record row) { + if (row == null + || !Boolean.FALSE.equals(row.get("script_only", Boolean.class)) + || row.get("script_patch_version", String.class) != null) { + throw new IllegalStateException("PUBLICATION_RELEASE_NOT_FULL_VERSION"); + } + var mapper = new ObjectMapper(); + List participants = + mapper.readValue( + row.get("participant_digests_json", String.class), new TypeReference<>() {}); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("published_release_bundle_ref", String.class), + row.get("version_number", Integer.class), + row.get("attestation_schema_version", String.class), + row.get("publish_workflow_id", String.class), + row.get("manifest_hash", String.class), + row.get("manifest_schema_version", Integer.class), + mapper.readValue( + row.get("artifact_digests_json", String.class), + new TypeReference>() {}), + mapper.readValue( + row.get("required_manifest_asset_keys_json", String.class), + new TypeReference>() {}), + participants.stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(), + mapper.readValue( + row.get("command_definitions_json", String.class), + new TypeReference>() {}), + row.get("generation_config_revision", String.class), + WorldPublishedStartLocationEvidence.fromStored( + row.get("world_published_start_location_evidence_json", String.class) + .getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java new file mode 100644 index 0000000000..cb62ef5bbc --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; + +/** Actual owner application result, returned only after the atomic source write/readback. */ +public record RealmPolicyApplication( + RealmPolicyGenesis genesis, + UUID inheritedCommitId, + String expectedEpoch, + RealmPolicySnapshot snapshot) { + public RealmPolicyApplication( + UUID inheritedCommitId, String expectedEpoch, RealmPolicySnapshot snapshot) { + this(null, inheritedCommitId, expectedEpoch, snapshot); + } + + public RealmPolicyApplication { + if ((inheritedCommitId == null && genesis == null) + || new UUID(0, 0).equals(inheritedCommitId) + || (genesis != null && !genesis.target().equals(snapshot.binding().target())) + || expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) { + throw new IllegalArgumentException("Policy application must advance its exact source epoch"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(out, genesis == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, genesis == null ? new byte[0] : genesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inheritedCommitId == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public OwnerOutcome ownerOutcome() { + var binding = snapshot.binding(); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "realm-policy:" + binding.commitId(), + canonicalBytes(), + List.of( + new AppliedEpoch( + RealmPolicySource.SCOPE, + binding.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch, + snapshot.sourceEpoch()))); + } + + /** Parent composes actual sibling source evidence and its complete exact epoch vector once. */ + public OwnerOutcome combinedOwnerOutcome( + byte[] siblingEvidence, List completeEpochs) { + if (siblingEvidence == null || siblingEvidence.length == 0) { + throw new IllegalArgumentException("Actual sibling owner application evidence required"); + } + var binding = snapshot.binding(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, siblingEvidence); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "control-plane-source:" + binding.commitId(), + out.toByteArray(), + completeEpochs); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java new file mode 100644 index 0000000000..af88d5d246 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Empty new-Draft baseline receipt, distinct from every actual authored commit. */ +public record RealmPolicyGenesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public RealmPolicyGenesis { + if (target == null + || receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact persisted new-Draft genesis identity required"); + } + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-genesis/v1", + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId, + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java new file mode 100644 index 0000000000..eaa92ba7dc --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.dao.DataAccessException; +import org.springframework.grpc.server.service.GrpcService; + +/** Protected read adapter; the owner-read opt-in condition controls runtime registration. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.game-design.published-realm-entry-policy-read", + name = "enabled", + havingValue = "true") +public final class RealmPolicyPublicationGrpcService + extends PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase { + private final RealmPolicyPublicationService owner; + private final String namespace; + + public RealmPolicyPublicationGrpcService( + RealmPolicyPublicationService owner, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void resolvePublishedRealmEntryPolicy( + ResolvePublishedRealmEntryPolicyRequest wire, + StreamObserver observer) { + if (!requireGameSessionPeer(observer)) return; + + final PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest request; + try { + request = PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "Canonical schema-1 realm policy read required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED, "Realm policy target namespace differs from peer"); + return; + } + + final PublishedRealmEntryPolicySetEvidence evidence; + try { + Optional stored = + owner.readPublishedSet(request.canonicalTenantId(), request.canonicalVersionId()); + if (stored.isEmpty()) { + fail(observer, Status.NOT_FOUND, "Published realm policy set not found"); + return; + } + RealmPolicyPublishedEvidence.PublishedSet ownerSet = stored.orElseThrow(); + requireExactTarget( + request.canonicalTenantId(), request.canonicalVersionId(), ownerSet.target()); + evidence = RealmPolicyPublishedEvidenceMapper.toShared(ownerSet); + if (!containsSelector(evidence, request.worldSlug(), request.realmSlug())) { + fail(observer, Status.NOT_FOUND, "Published realm policy selector not found"); + return; + } + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy owner read failed"); + return; + } + + final ResolvePublishedRealmEntryPolicyResponse response; + try { + response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy response encoding failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest wire, + StreamObserver observer) { + if (!requireGameSessionPeer(observer)) return; + + final PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request; + try { + request = PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "Canonical schema-1 realm policy read required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED, "Realm policy target namespace differs from peer"); + return; + } + + final PublishedRealmEntryPolicySetEvidence evidence; + try { + Optional stored = + owner.readPublishedSet(request.canonicalTenantId(), request.canonicalVersionId()); + if (stored.isEmpty()) { + fail(observer, Status.NOT_FOUND, "Published realm policy set not found"); + return; + } + RealmPolicyPublishedEvidence.PublishedSet ownerSet = stored.orElseThrow(); + requireExactTarget( + request.canonicalTenantId(), request.canonicalVersionId(), ownerSet.target()); + evidence = RealmPolicyPublishedEvidenceMapper.toShared(ownerSet); + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy owner read failed"); + return; + } + + final ListPublishedRealmEntryPoliciesResponse response; + try { + response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail(observer, Status.FAILED_PRECONDITION, "Published realm policy evidence is inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Published realm policy response encoding failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private boolean requireGameSessionPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + if (peer == null + || !peer.uri().equals(expectedPeer) + || !peer.namespace().equals(namespace) + || !peer.service().equals("game-session-service") + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Session workload without end-user context required"); + return false; + } + return true; + } + + private static boolean containsSelector( + PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { + return evidence.policies().stream() + .anyMatch( + policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug)); + } + + private static void requireExactTarget( + java.util.UUID tenantId, + java.util.UUID versionId, + net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof target) { + if (!target.canonicalTenantId().equals(tenantId) + || !target.canonicalVersionId().equals(versionId)) { + throw new IllegalStateException("Published policy owner returned a different target"); + } + } + + private static void fail(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java new file mode 100644 index 0000000000..3e160cd10f --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -0,0 +1,565 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal immutable policy association; all writes join the actual Game Design seal transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class RealmPolicyPublicationRepository { + private static final int MAX_POLICY_ROWS = RealmPolicySource.MAX_POLICIES; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final DSLContext dsl; + + public RealmPolicyPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Retains an association only from the operation's actual sealed PUBLISHED owner readback. A + * release with no policy source/capture remains a valid unrelated release and creates no row. + */ + public Optional retainSealedPublished( + String publishWorkflowId) { + requireWrite(); + if (publishWorkflowId == null || publishWorkflowId.isBlank()) { + throw new IllegalArgumentException("Exact publication workflow required"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || operationReadback.terminalEvidenceBytes() == null) { + throw new IllegalStateException("POLICY_PUBLICATION_REQUIRES_SEALED_PUBLISHED_OPERATION"); + } + var operation = operationReadback.operation(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(operationReadback.terminalEvidenceBytes()); + if (!operation.workflowId().equals(publishWorkflowId) + || terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_BINDING_CONFLICT"); + } + TargetProof target = operation.account().input().selection().target(); + var sourceRepository = new RealmPolicySourceRepository(dsl); + Optional captureResult = sourceRepository.readCapture(operation); + if (captureResult.isEmpty()) { + if (sourceExists(target) || selectedCommitDeclaresRealmPolicy(operation)) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + } + return Optional.empty(); + } + var capture = captureResult.orElseThrow(); + if (!capture.operation().equals(operation) + || !capture.snapshot().binding().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_BINDING_CONFLICT"); + } + + var existing = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (existing != null) { + var retained = readPublishedSet(target, existing).orElseThrow(); + requireExactRetry(retained, operation, capture, terminal); + return Optional.of(retained); + } + + requireOwner(target, terminal, true); + requireCurrentVisibleSource(target, capture.snapshot()); + requireActualRelease(operation, terminal); + + var release = terminal.releaseContent(); + var rows = new ArrayList(); + for (RealmPolicySource.Policy source : capture.snapshot().policies()) { + UUID id = UUID.randomUUID(); + rows.add( + new RealmPolicyPublishedEvidence.Policy( + id, + source, + RealmPolicyPublishedEvidence.policyDigest( + id, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source))); + } + List orderedSources = + RealmPolicySource.ordered( + rows.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList()); + if (!orderedSources.equals(capture.snapshot().policies()) + || rows.size() != capture.snapshot().policies().size()) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_SET_CHANGED"); + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + rows); + + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, " + + "source_commit_id, source_epoch, target_proof_json, operation_bytes, capture_bytes, " + + "terminal_evidence_bytes, release_content_bytes, published_release_bundle_ref, " + + "published_release_bundle_digest, publish_workflow_id, manifest_hash, " + + "publication_version_state_epoch, policy_count, policy_set_digest, sealed) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + RealmPolicyPublishedEvidence.targetProofJson(target), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + release.canonicalBytes(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + rows.size(), + setDigest); + + for (int ordinal = 0; ordinal < rows.size(); ordinal++) { + var row = rows.get(ordinal); + var source = row.source(); + var policy = source.policy(); + dsl.execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + ordinal, + row.policyId(), + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + row.policyDigest(), + policy.visible(), + policy.publicProduction()); + } + int sealed = + dsl.execute( + "UPDATE game_design_published_realm_policy_set SET sealed = TRUE " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND sealed = FALSE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (sealed != 1) throw new IllegalStateException("POLICY_PUBLICATION_SET_SEAL_CONFLICT"); + + var stored = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (stored == null) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_READBACK_UNAVAILABLE"); + } + var readback = readPublishedSet(target, stored).orElseThrow(); + requireExactRetry(readback, operation, capture, terminal); + return Optional.of(readback); + } + + /** + * Caller supplies a REPEATABLE_READ snapshot; no caller state substitutes for stored evidence. + */ + public Optional readPublishedSet( + UUID canonicalTenantId, UUID canonicalVersionId) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Canonical policy target resolution requires one read-only REPEATABLE_READ snapshot"); + } + var version = + // Exact read uses the transaction-bound search path, not the migration-only lock API. + new VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId(canonicalTenantId, canonicalVersionId); + if (version.isEmpty()) return Optional.empty(); + var owner = version.orElseThrow(); + return readPublishedSet( + new TargetProof( + owner.getCanonicalTenantId(), + owner.getCanonicalVersionId(), + owner.getId(), + owner.getTenantId(), + owner.getIdentitySourceGameRowId(), + owner.getIdentitySourceGameTenantKey(), + owner.getIdentitySourceProvenanceKind())); + } + + /** Exact internal target read; the service owns its independent snapshot boundary. */ + public Optional readPublishedSet(TargetProof target) { + Objects.requireNonNull(target, "target"); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? Optional.empty() : readPublishedSet(target, row); + } + + private Optional readPublishedSet( + TargetProof target, Record header) { + if (!Boolean.TRUE.equals(header.get("sealed", Boolean.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_INCOMPLETE"); + } + if (!Objects.equals( + header.get("target_proof_json", String.class), + RealmPolicyPublishedEvidence.targetProofJson(target)) + || !Objects.equals( + header.get("canonical_tenant_id", UUID.class), target.canonicalTenantId()) + || !Objects.equals( + header.get("canonical_version_id", UUID.class), target.canonicalVersionId()) + || !Objects.equals( + header.get("game_design_version_row_id", Long.class), + target.gameDesignVersionRowId())) { + throw new IllegalStateException("POLICY_PUBLICATION_TARGET_PROOF_CONFLICT"); + } + + byte[] operationBytes = header.get("operation_bytes", byte[].class); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_TARGET_CONFLICT"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || !Arrays.equals(operationReadback.operation().canonicalBytes(), operationBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_NOT_SEALED"); + } + byte[] terminalBytes = operationReadback.terminalEvidenceBytes(); + byte[] retainedTerminalBytes = header.get("terminal_evidence_bytes", byte[].class); + if (terminalBytes == null || !Arrays.equals(terminalBytes, retainedTerminalBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_CHANGED"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + var release = terminal.releaseContent(); + if (!Arrays.equals(release.canonicalBytes(), header.get("release_content_bytes", byte[].class)) + || !Objects.equals( + release.publishedReleaseBundleRef(), + header.get("published_release_bundle_ref", String.class)) + || !Objects.equals( + terminal.publishedReleaseBundleDigest(), + header.get("published_release_bundle_digest", String.class)) + || !Objects.equals( + release.publishWorkflowId(), header.get("publish_workflow_id", String.class)) + || !Objects.equals(release.manifestHash(), header.get("manifest_hash", String.class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + header.get("publication_version_state_epoch", Long.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CHANGED"); + } + + Record version = requireOwner(target, terminal, false); + int versionNumber = header.get("version_number", Integer.class); + if (release.versionNumber() != versionNumber + || version.get("version_number", Integer.class) != versionNumber) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NUMBER_CHANGED"); + } + var sourceRepository = new RealmPolicySourceRepository(dsl); + var capture = + sourceRepository + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE")); + byte[] captureBytes = header.get("capture_bytes", byte[].class); + if (!Arrays.equals(capture.canonicalBytes(), captureBytes) + || !capture.snapshot().binding().target().equals(target) + || !Objects.equals( + capture.snapshot().binding().commitId(), header.get("source_commit_id", UUID.class)) + || !Objects.equals( + capture.snapshot().sourceEpoch(), header.get("source_epoch", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_CHANGED"); + } + requireCurrentVisibleSource(target, capture.snapshot()); + + int expectedCount = header.get("policy_count", Integer.class); + if (expectedCount < 1 || expectedCount > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_OVERSIZED_OR_EMPTY"); + } + List storedRows = + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "ORDER BY ordinal LIMIT ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + MAX_POLICY_ROWS + 1); + if (storedRows.size() != expectedCount || storedRows.size() > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_CARDINALITY_CONFLICT"); + } + List policies = new ArrayList<>(); + for (int ordinal = 0; ordinal < storedRows.size(); ordinal++) { + Record row = storedRows.get(ordinal); + RealmPolicySource.Policy source = sourcePolicy(row); + if (!Objects.equals(row.get("ordinal", Integer.class), ordinal)) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_ORDER_CONFLICT"); + } + policies.add( + new RealmPolicyPublishedEvidence.Policy( + row.get("realm_policy_id", UUID.class), + source, + row.get("policy_digest", String.class))); + } + List expectedPolicies = capture.snapshot().policies(); + if (!expectedPolicies.equals( + policies.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_ROWS_CHANGED"); + } + for (var policy : policies) { + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policy.policyId(), + target, + versionNumber, + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + policy.source()); + if (!digest.equals(policy.policyDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_POLICY_DIGEST_CONFLICT"); + } + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies); + if (!setDigest.equals(header.get("policy_set_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_DIGEST_CONFLICT"); + } + return Optional.of( + new RealmPolicyPublishedEvidence.PublishedSet( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + expectedCount, + setDigest, + policies)); + } + + private RealmPolicySource.Policy sourcePolicy(Record row) { + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical(row.get("policy_json", String.class), JSON); + if (!Objects.equals(row.get("world_slug", String.class), policy.worldSlug()) + || !Objects.equals(row.get("realm_slug", String.class), policy.realmSlug()) + || !Objects.equals(row.get("visible", Boolean.class), policy.visible()) + || !Objects.equals( + row.get("public_production", Boolean.class), policy.publicProduction())) { + throw new IllegalStateException("POLICY_PUBLICATION_TYPED_POLICY_CONFLICT"); + } + return new RealmPolicySource.Policy( + row.get("source_commit_id", UUID.class), + row.get("source_revision_id", UUID.class), + row.get("logical_revision_id", String.class), + policy); + } + + /** This reads without acquiring earlier publication locks; the seal already holds Version. */ + private Record requireOwner( + TargetProof target, GameDesignPublicationTerminalEvidence terminal, boolean atSeal) { + Record owner = + dsl.fetchOne( + "SELECT v.version_state, v.version_state_epoch, v.version_number, v.is_script_only, " + + "v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND g.id = ? AND g.tenant_id = ? AND g.canonical_tenant_id = ? " + + "AND g.tenant_identity_provenance_kind = ? AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.canonicalTenantId(), + target.sourceProvenanceKind()); + if (owner == null + || !Boolean.FALSE.equals(owner.get("is_script_only", Boolean.class)) + || owner.get("script_patch_version", String.class) != null + || owner.get("base_version_id", Long.class) != null) { + throw new IllegalStateException("POLICY_PUBLICATION_CANONICAL_OWNER_UNAVAILABLE"); + } + String state = owner.get("version_state", String.class); + long epoch = owner.get("version_state_epoch", Long.class); + if (atSeal) { + if (!"PUBLISHED".equals(state) || epoch != terminal.publicationVersionStateEpoch()) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_AT_SEAL"); + } + } else if (("PUBLISHED".equals(state) && epoch != terminal.publicationVersionStateEpoch()) + || ("ACTIVE".equals(state) && epoch <= terminal.publicationVersionStateEpoch()) + || (!"PUBLISHED".equals(state) && !"ACTIVE".equals(state))) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_CURRENT"); + } + return owner; + } + + private void requireCurrentVisibleSource(TargetProof target, RealmPolicySnapshot snapshot) { + Record source = + dsl.fetchOne( + "SELECT source_epoch, visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (source == null + || !Objects.equals(source.get("source_epoch", String.class), snapshot.sourceEpoch()) + || !Objects.equals( + source.get("visible_commit_id", UUID.class), snapshot.binding().commitId())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_VISIBILITY_CHANGED"); + } + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(target) + .orElseThrow( + () -> new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_UNAVAILABLE")); + if (!fence.commitId().equals(snapshot.binding().commitId()) + || !fence.requestId().equals(snapshot.binding().requestId()) + || !fence.inputDigest().equals(snapshot.binding().digest())) { + throw new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_CHANGED"); + } + } + + private void requireActualRelease( + GameDesignPublicationOperation operation, GameDesignPublicationTerminalEvidence terminal) { + Record row = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (row == null) throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_UNAVAILABLE"); + var release = PublicationReleaseContent.fromRow(row); + if (!Arrays.equals(release.canonicalBytes(), terminal.releaseContent().canonicalBytes()) + || !Objects.equals(row.get("publish_workflow_id", String.class), operation.workflowId()) + || !Objects.equals( + row.get("published_release_bundle_ref", String.class), + terminal.publishedReleaseBundleRef()) + || !Objects.equals(terminal.publishedReleaseBundleDigest(), release.contentDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CONFLICT"); + } + } + + private boolean sourceExists(TargetProof target) { + return dsl.fetchExists( + dsl.selectOne() + .from("game_design_realm_policy_source") + .where( + "canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private boolean selectedCommitDeclaresRealmPolicy(GameDesignPublicationOperation operation) { + return operation.account().input().selection().selectedCommit().revisions().stream() + .filter(revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .anyMatch( + revision -> { + JsonNode root = RealmPolicySource.tree(revision.payload()); + return root.path("revisionKind").isTextual() + && RealmEntryPolicy.REVISION_KIND.equals(root.path("revisionKind").asText()); + }); + } + + private void requireExactRetry( + RealmPolicyPublishedEvidence.PublishedSet retained, + GameDesignPublicationOperation operation, + RealmPolicySnapshot.Capture capture, + GameDesignPublicationTerminalEvidence terminal) { + if (!Arrays.equals(retained.operationBytes(), operation.canonicalBytes()) + || !Arrays.equals(retained.captureBytes(), capture.canonicalBytes()) + || !Arrays.equals(retained.terminalEvidenceBytes(), terminal.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_IDENTITY_CONFLICT"); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Published policy association requires the owner READ_COMMITTED seal transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java new file mode 100644 index 0000000000..1af6a81893 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered internal API for binding a typed source capture to a sealed Game Design release. */ +public final class RealmPolicyPublicationService { + private final RealmPolicyPublicationRepository repository; + private final TransactionTemplate read; + + public RealmPolicyPublicationService( + RealmPolicyPublicationRepository repository, PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + read = new TransactionTemplate(Objects.requireNonNull(transactions)); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + /** + * Call immediately after the real PUBLISHED operation seal, inside the same owner transaction. + * The repository rereads the operation and its immutable terminal evidence before writing. + */ + public Optional retainSealedPublished( + String publishWorkflowId) { + return repository.retainSealedPublished(publishWorkflowId); + } + + /** Independent complete-set read; it never establishes runtime catalog or admission authority. */ + public Optional readPublishedSet( + UUID canonicalTenantId, UUID canonicalVersionId) { + requireIndependentRead(); + return read.execute( + status -> repository.readPublishedSet(canonicalTenantId, canonicalVersionId)); + } + + /** Internal complete-target read for owner composition, never caller-provided numeric aliases. */ + public Optional readPublishedSet(TargetProof target) { + requireIndependentRead(); + return read.execute(status -> repository.readPublishedSet(target)); + } + + /** Exact selector lookup over the independently verified complete set. */ + public Optional readPublishedPolicy( + TargetProof target, String worldSlug, String realmSlug) { + if (!net.firedevops.firemud.common.publication.RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !net.firedevops.firemud.common.publication.RealmEntryPolicy.isCanonicalSlug(realmSlug)) { + throw new IllegalArgumentException("Canonical realm policy selectors required"); + } + return readPublishedSet(target) + .flatMap( + set -> + set.policies().stream() + .filter( + policy -> + policy.source().policy().worldSlug().equals(worldSlug) + && policy.source().policy().realmSlug().equals(realmSlug)) + .findFirst()); + } + + private static void requireIndependentRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Published policy readback requires an independent REPEATABLE_READ transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java new file mode 100644 index 0000000000..11354f8803 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; + +/** Immutable internal evidence associating a frozen source set with its actual sealed release. */ +public final class RealmPolicyPublishedEvidence { + public static final String SET_DIGEST_SCHEMA = + PublishedRealmEntryPolicySetEvidence.SET_DIGEST_SCHEMA; + public static final String POLICY_DIGEST_SCHEMA = + PublishedRealmEntryPolicySetEvidence.POLICY_DIGEST_SCHEMA; + + private RealmPolicyPublishedEvidence() {} + + /** One Game Design allocated immutable identity for one effective authored policy. */ + public record Policy(UUID policyId, RealmPolicySource.Policy source, String policyDigest) { + public Policy { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical policy digest required"); + } + } + } + + /** Complete immutable set and the original owner evidence that authorized its publication. */ + public record PublishedSet( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public PublishedSet { + Objects.requireNonNull(target, "target"); + nonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0 + || sourceEpoch == null + || !sourceEpoch.matches("0|[1-9][0-9]*") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !digest(publishedReleaseBundleDigest) + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || !digest(manifestHash) + || publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Complete publication-bound policy identity required"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 + || policyCount > RealmPolicySource.MAX_POLICIES + || policyCount != policies.size() + || !digest(policySetDigest)) { + throw new IllegalArgumentException("Complete bounded policy-set evidence required"); + } + RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target) + || !operation.workflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException("Publication evidence differs from exact TargetProof"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + var release = terminal.releaseContent(); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes) + || !release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + if (!computePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + } + + public static String targetProofJson(DraftCommitBinding.TargetProof target) { + return PublishedRealmEntryPolicySetEvidence.targetProofJson(target); + } + + public static String policyDigest( + UUID policyId, + DraftCommitBinding.TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + RealmPolicySource.Policy source) { + Objects.requireNonNull(source, "source"); + return PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + source.policy()); + } + + public static String computePolicySetDigest( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + var shared = + policies.stream() + .map( + policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) + .toList(); + return PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + shared); + } + + private static byte[] nonEmptyCopy(byte[] bytes, String name) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return bytes.clone(); + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static void nonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + name + " required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java new file mode 100644 index 0000000000..ac368131db --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; + +/** Pure mapping from the verified Game Design owner result into the shared sealed-set carrier. */ +final class RealmPolicyPublishedEvidenceMapper { + private RealmPolicyPublishedEvidenceMapper() {} + + static PublishedRealmEntryPolicySetEvidence toShared( + RealmPolicyPublishedEvidence.PublishedSet source) { + Objects.requireNonNull(source, "source"); + var policies = + source.policies().stream() + .map( + policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) + .toList(); + var candidate = + new PublishedRealmEntryPolicySetEvidence( + source.target(), + source.versionNumber(), + source.sourceCommitId(), + source.sourceEpoch(), + source.publishedReleaseBundleRef(), + source.publishedReleaseBundleDigest(), + source.publishWorkflowId(), + source.manifestHash(), + source.publicationVersionStateEpoch(), + source.operationBytes(), + source.captureBytes(), + source.terminalEvidenceBytes(), + source.policyCount(), + source.policySetDigest(), + policies); + return PublishedRealmEntryPolicySetEvidence.fromStored(candidate.canonicalBytes()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java new file mode 100644 index 0000000000..a024a75b5a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective source at one synchronized fence, including original revision provenance. */ +public record RealmPolicySnapshot( + DraftCommitBinding binding, String sourceEpoch, List policies) { + public RealmPolicySnapshot { + if (binding == null || sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact source binding and canonical epoch required"); + } + policies = RealmPolicySource.draftOrdered(policies); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "policies", + RealmPolicySource.tree(RealmPolicySource.policiesJson(policies)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public static RealmPolicySnapshot fromStored(String json) { + var node = RealmPolicySource.tree(json); + RealmPolicySource.fields( + node, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!"game-design-realm-policy-snapshot/v1".equals(RealmPolicySource.text(node, "schema"))) { + throw new IllegalArgumentException("Unsupported policy snapshot schema"); + } + var result = + new RealmPolicySnapshot( + DraftCommitBinding.fromStored( + RealmPolicySource.text(node, "bindingJson"), + RealmPolicySource.text(node, "bindingDigest")), + RealmPolicySource.text(node, "sourceEpoch"), + RealmPolicySource.policiesFromStored(node.get("policies").toString())); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Policy snapshot bytes changed"); + return result; + } + + /** Frozen source only. No terminal association or PUBLISHED claim is represented here. */ + public record Capture(GameDesignPublicationOperation operation, RealmPolicySnapshot snapshot) { + public Capture { + RealmPolicySource.ordered(snapshot.policies()); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen policy snapshot differs from original selected commit"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java new file mode 100644 index 0000000000..504e5cc3e9 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Owner-local typed source; neither these bytes nor a caller's declaration grant authority. */ +public final class RealmPolicySource { + private static final ObjectMapper JSON = new ObjectMapper(); + public static final String SCOPE = "REALM_ENTRY_POLICY_SET"; + public static final int MAX_POLICIES = 128; + + private RealmPolicySource() {} + + /** Original authored UUID and logical identity survive every inherited snapshot. */ + public record Policy( + UUID commitId, UUID revisionId, String logicalRevisionId, RealmEntryPolicy policy) { + public Policy { + nonNil(commitId); + nonNil(revisionId); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + policy = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), JSON); + } + } + + /** Closed owner payload, distinct from the policy JSON itself. */ + public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { + var kind = text(tree(input.payload()), "revisionKind"); + if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; + if ("COMMAND_DEFINITION".equals(kind)) return false; + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + + public static Policy revision( + DraftCommitBinding binding, DraftCommitBinding.RevisionPayload input) { + if (input.owner() != DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) { + throw new IllegalArgumentException("Policy revision belongs to Game Design control plane"); + } + JsonNode root = tree(input.payload()); + fields(root, "revisionKind", "logicalRevisionId", "policy"); + if (!RealmEntryPolicy.REVISION_KIND.equals(text(root, "revisionKind"))) { + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + return new Policy( + binding.commitId(), + input.revisionId(), + text(root, "logicalRevisionId"), + RealmEntryPolicy.parse(root.get("policy").toString(), JSON)); + } + + public static List effective(List inherited, List updates) { + Map policies = new LinkedHashMap<>(); + for (Policy policy : draftOrdered(inherited)) policies.put(selector(policy), policy); + var seen = new HashSet(); + for (Policy policy : updates) { + if (!seen.add(selector(policy))) { + throw new IllegalArgumentException("A commit repeats a policy selector"); + } + policies.put(selector(policy), policy); + } + return draftOrdered(new ArrayList<>(policies.values())); + } + + public static List ordered(List policies) { + var ordered = draftOrdered(policies); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete policy set must contain 1 through 128 policies"); + } + int production = 0; + for (Policy policy : policies) { + if (policy.policy().visible() && policy.policy().publicProduction()) production++; + } + if (production != 1) { + throw new IllegalArgumentException("Exactly one visible public-production realm required"); + } + return ordered; + } + + /** Draft source may be empty or not yet publication-complete. */ + public static List draftOrdered(List policies) { + if (policies.size() > MAX_POLICIES) + throw new IllegalArgumentException("Draft policy set exceeds 128 policies"); + var realms = new HashSet(); + var revisions = new HashSet(); + for (Policy policy : policies) { + if (!realms.add(policy.policy().realmSlug()) || !revisions.add(policy.revisionId())) { + throw new IllegalArgumentException("Duplicate tenant realm selector or authored revision"); + } + } + return policies.stream() + .sorted( + Comparator.comparing((Policy p) -> p.policy().worldSlug()) + .thenComparing(p -> p.policy().realmSlug())) + .toList(); + } + + static String policiesJson(List policies) { + return canonical( + draftOrdered(policies).stream() + .map( + policy -> + Map.of( + "commitId", + policy.commitId().toString(), + "revisionId", + policy.revisionId().toString(), + "logicalRevisionId", + policy.logicalRevisionId(), + "policy", + tree(policy.policy().canonicalJson()))) + .toList()); + } + + static List policiesFromStored(String bytes) { + JsonNode root = tree(bytes); + if (!root.isArray() || root.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete stored policy array required"); + } + var policies = new ArrayList(); + for (JsonNode node : root) { + fields(node, "commitId", "revisionId", "logicalRevisionId", "policy"); + policies.add( + new Policy( + UUID.fromString(text(node, "commitId")), + UUID.fromString(text(node, "revisionId")), + text(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(node.get("policy").toString(), JSON))); + } + var result = draftOrdered(policies); + if (!policiesJson(result).equals(bytes)) { + throw new IllegalArgumentException("Stored policy snapshot is not canonical"); + } + return result; + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical owner source encoding failed", failure); + } + } + + static JsonNode tree(String value) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(value)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous owner source JSON required", failure); + } + } + + static void fields(JsonNode node, String... fields) { + if (!node.isObject() || node.size() != fields.length) { + throw new IllegalArgumentException("Closed owner source fields required"); + } + for (String field : fields) + if (!node.has(field)) throw new IllegalArgumentException("Missing " + field); + } + + static String text(JsonNode node, String field) { + if (!node.path(field).isTextual()) + throw new IllegalArgumentException("Text required: " + field); + return node.get(field).asText(); + } + + private static String selector(Policy policy) { + return policy.policy().worldSlug() + "/" + policy.policy().realmSlug(); + } + + private static void nonNil(UUID value) { + if (value == null || new UUID(0, 0).equals(value)) + throw new IllegalArgumentException("Non-nil authored UUID required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java new file mode 100644 index 0000000000..a68f69c8e1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -0,0 +1,607 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage, with no runtime registration or creator authorization. Missing actual + * source baseline denies. Empty genesis can only be enrolled in the actual Version insert + * transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner storage collaborator.") +public final class RealmPolicySourceRepository { + private final DSLContext dsl; + + public RealmPolicySourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Parent invokes only from the new Version insert branch, in that same owner transaction. */ + public RealmPolicyGenesis recordFreshGenesis(TargetProof target) { + requireWrite(); + lockAuthority(target); + var prior = readGenesis(target); + if (prior.isPresent()) return prior.orElseThrow(); + requireDraftAndUnfrozen(target); + var witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); + var receipt = new RealmPolicyGenesis(target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_realm_policy_genesis " + + "(canonical_tenant_id, canonical_version_id, receipt_id, version_id, creation_transaction_id, receipt_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId(), + target.gameDesignVersionRowId(), + receipt.creationTransactionId(), + receipt.canonicalJson()); + dsl.execute( + "INSERT INTO game_design_realm_policy_source " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, genesis_receipt_id) VALUES (?, ?, '0', NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId()); + return readGenesis(target).orElseThrow(); + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var receipt = + new RealmPolicyGenesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (!receipt.canonicalJson().equals(row.get("receipt_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) { + throw new IllegalStateException("POLICY_GENESIS_TARGET_CONFLICT"); + } + return Optional.of(receipt); + } + + /** Caller must already own the authorized coordinator application slot. */ + public RealmPolicyApplication apply(DraftCommitBinding binding) { + requirePolicyOnly(binding); + var result = applyMutation(binding); + recordCompleteOwnerOutcome(binding, result.ownerOutcome()); + return result; + } + + /** + * Stages only policy mutation evidence; parent records one complete owner outcome before commit. + */ + public RealmPolicyApplication applyMutation(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + var prior = application(binding); + if (prior.isPresent()) { + var result = prior.orElseThrow(); + return result; + } + requireDraftAndUnfrozen(binding.target()); + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_ALREADY_RESERVED"); + } + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var slot = + coordinator + .readApplicationSlot(binding.target()) + .orElseThrow(() -> new IllegalStateException("POLICY_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("POLICY_APPLICATION_SLOT_CHANGED"); + } + var state = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && state.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("POLICY_OWNER_APPLICATION_NOT_STARTED"); + } + var source = source(binding.target()); + UUID inherited = source.get("visible_commit_id", UUID.class); + String epoch = source.get("source_epoch", String.class); + var genesis = + source.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(); + if (genesis != null + && !genesis.receiptId().equals(source.get("genesis_receipt_id", UUID.class))) { + throw new IllegalStateException("POLICY_GENESIS_SOURCE_CONFLICT"); + } + List inheritedPolicies; + if (inherited == null) { + if (genesis == null + || !"0".equals(epoch) + || new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .isPresent()) { + throw new IllegalStateException("POLICY_SOURCE_GENESIS_NOT_CURRENT"); + } + inheritedPolicies = List.of(); + } else { + requireCurrentFence(binding.target(), inherited); + var previous = readSnapshot(binding.target(), inherited).orElseThrow(); + if (!previous.sourceEpoch().equals(epoch)) + throw new IllegalStateException("POLICY_SOURCE_UNSYNCHRONIZED"); + inheritedPolicies = previous.policies(); + } + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(u -> RealmPolicySource.SCOPE.equals(u.aggregateType())) + .toList(); + if (units.size() != 1 + || !RealmPolicySource.SCOPE.equals(units.getFirst().aggregateType()) + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !RealmPolicySource.SCOPE.equals(units.getFirst().scopeType()) + || !"effective".equals(units.getFirst().scopeId()) + || !epoch.equals(units.getFirst().expectedEpoch())) { + throw new IllegalArgumentException( + "Complete policy-set containing scope and exact epoch required"); + } + var updates = + binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(r -> RealmPolicySource.revision(binding, r)) + .toList(); + if (updates.isEmpty()) + throw new IllegalArgumentException("Typed authored policy revisions required"); + for (var update : updates) { + if (dsl.fetchExists( + dsl.selectOne() + .from("game_design_realm_policy_application") + .where( + "canonical_tenant_id = ? AND canonical_version_id = ? AND snapshot_json::jsonb -> 'policies' @> ?::jsonb", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + RealmPolicySource.canonical( + List.of(java.util.Map.of("revisionId", update.revisionId().toString())))))) { + throw new IllegalArgumentException("Authored policy revision identity cannot be reused"); + } + if (inheritedPolicies.stream().anyMatch(p -> p.revisionId().equals(update.revisionId()))) { + throw new IllegalArgumentException("Authored baseline revision identity cannot be reused"); + } + } + var snapshot = + new RealmPolicySnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + RealmPolicySource.effective(inheritedPolicies, updates)); + var result = new RealmPolicyApplication(genesis, inherited, epoch, snapshot); + int advanced = + dsl.execute( + "UPDATE game_design_realm_policy_source SET source_epoch = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited); + if (advanced != 1) throw new IllegalStateException("POLICY_SOURCE_EPOCH_CONFLICT"); + dsl.execute( + "INSERT INTO game_design_realm_policy_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, genesis_receipt_id, expected_epoch, snapshot_json, result_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + inherited, + genesis == null ? null : genesis.receiptId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + var retained = application(binding).orElseThrow(); + return retained; + } + + /** Parent supplies actual sibling evidence and every exact owned epoch to one shared result. */ + public void recordCombinedOwnerOutcome( + DraftCommitBinding binding, + byte[] siblingEvidence, + List completeEpochs) { + requireWrite(); + lockAuthority(binding.target()); + var result = application(binding).orElseThrow(); + recordCompleteOwnerOutcome( + binding, result.combinedOwnerOutcome(siblingEvidence, completeEpochs)); + } + + private void recordCompleteOwnerOutcome( + DraftCommitBinding binding, DraftCommitCoordinatorRepository.OwnerOutcome outcome) { + requireWrite(); + var row = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) throw new IllegalStateException("POLICY_OWNER_APPLICATION_UNAVAILABLE"); + byte[] previous = row.get(0, byte[].class); + if (previous != null && !Arrays.equals(previous, outcome.resultBytes())) { + throw new IllegalArgumentException("POLICY_COMPLETE_OWNER_RESULT_CHANGED"); + } + new DraftCommitCoordinatorRepository(dsl).recordOwnerOutcome(binding, outcome); + if (previous == null) + dsl.execute( + "UPDATE game_design_realm_policy_application SET owner_result_bytes = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + outcome.resultBytes(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + requireCoordinatorResult(application(binding).orElseThrow()); + } + + private static void requirePolicyOnly(DraftCommitBinding binding) { + if (binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .anyMatch(r -> !RealmPolicySource.isPolicyRevision(r)) + || binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .anyMatch(u -> !RealmPolicySource.SCOPE.equals(u.aggregateType()))) { + throw new IllegalArgumentException( + "Mixed Game Design commit requires one combined owner result"); + } + } + + /** + * Invoke in the transaction that advances the coordinator fence, before releasing its slot. A + * disjoint synchronized commit inherits the last complete snapshot; staged owner rows never + * become visible. Absence of a baseline is a denial, including for retained content. + */ + public RealmPolicySnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + requireCurrentFence(binding.target(), binding.commitId()); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("POLICY_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + requireDraftAndUnfrozen(binding.target()); + var source = source(binding.target()); + UUID previousCommit = source.get("visible_commit_id", UUID.class); + var previous = + previousCommit == null + ? null + : readSnapshot(binding.target(), previousCommit).orElseThrow(); + if (previous == null + && (source.get("genesis_receipt_id", UUID.class) == null + || readGenesis(binding.target()).isEmpty())) { + throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + } + var applied = application(binding); + RealmPolicySnapshot snapshot; + if (binding.revisions().stream() + .anyMatch( + r -> + r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(r))) { + var result = + applied.orElseThrow(() -> new IllegalStateException("POLICY_OWNER_RESULT_UNAVAILABLE")); + requireCoordinatorResult(result); + if (!Objects.equals(result.inheritedCommitId(), previousCommit)) { + throw new IllegalStateException("POLICY_SNAPSHOT_PREDECESSOR_CHANGED"); + } + snapshot = result.snapshot(); + } else { + snapshot = + new RealmPolicySnapshot( + binding, + previous == null ? "0" : previous.sourceEpoch(), + previous == null ? List.of() : previous.policies()); + } + if (!snapshot.sourceEpoch().equals(source.get("source_epoch", String.class))) { + throw new IllegalStateException("PARTIAL_POLICY_OWNER_WRITE_NOT_VISIBLE"); + } + dsl.execute( + "INSERT INTO game_design_realm_policy_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, snapshot_json) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + previousCommit, + snapshot.canonicalJson()); + dsl.execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public RealmPolicySnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + var selection = operation.account().input().selection(); + var target = selection.target(); + lockAuthority(target); + var existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireDraftAndUnfrozen(target); + var row = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null + || !selection.canonicalJson().equals(row.get("selection_json", String.class)) + || !selection.digest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_UNAVAILABLE"); + } + // The Version lock serializes this check with the owner finalizer. Do not acquire its earlier + // game/attempt locks after the Version lock and invert the existing publication lock order. + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_SEALED"); + var versionEpoch = + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + Long persistedEpoch = versionEpoch == null ? null : versionEpoch.get(0, Long.class); + if (persistedEpoch == null || persistedEpoch <= 0) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_EPOCH_UNAVAILABLE"); + } + if (!selection.intent().expectedVersionStateEpoch().equals(Long.toString(persistedEpoch))) { + throw new IllegalStateException("POLICY_PUBLICATION_DRAFT_EPOCH_CHANGED"); + } + requireCurrentFence(target, selection.selectedCommit().commitId()); + var source = source(target); + var snapshot = readSnapshot(target, selection.selectedCommit().commitId()).orElseThrow(); + if (!source.get("visible_commit_id", UUID.class).equals(snapshot.binding().commitId()) + || !source.get("source_epoch", String.class).equals(snapshot.sourceEpoch())) { + throw new IllegalStateException("POLICY_FROZEN_SOURCE_NOT_SYNCHRONIZED"); + } + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_realm_policy_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class))) { + throw new IllegalArgumentException("POLICY_FREEZE_OPERATION_CONFLICT"); + } + var snapshot = readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow(); + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json FROM game_design_realm_policy_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId)) { + throw new IllegalStateException("POLICY_SNAPSHOT_OWNER_CONFLICT"); + } + exactCommit(snapshot.binding()); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId, + snapshot.binding().requestId()); + if (fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("POLICY_SNAPSHOT_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + for (var policy : snapshot.policies()) { + var authored = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + policy.commitId()); + if (authored == null) + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_UNAVAILABLE"); + var binding = + DraftCommitBinding.fromStored( + authored.get("binding_json", String.class), + authored.get("input_digest", String.class)); + var revision = + binding.revisions().stream() + .filter(r -> r.revisionId().equals(policy.revisionId())) + .findFirst() + .orElseThrow(); + if (!binding.target().equals(target) + || !RealmPolicySource.revision(binding, revision).equals(policy)) { + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_CHANGED"); + } + } + return Optional.of(snapshot); + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new RealmPolicyApplication( + row.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(), + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!result.snapshot().binding().equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_APPLICATION_EXACT_BINDING_CONFLICT"); + } + return Optional.of(result); + } + + private void requireCoordinatorResult(RealmPolicyApplication result) { + var binding = result.snapshot().binding(); + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + var stored = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (state == null + || state.outcome().isEmpty() + || stored == null + || !Arrays.equals(state.outcome().orElseThrow().resultBytes(), stored.get(0, byte[].class)) + || !state + .outcome() + .orElseThrow() + .appliedEpochs() + .contains(result.ownerOutcome().appliedEpochs().getFirst())) { + throw new IllegalStateException("POLICY_COORDINATOR_RESULT_CONFLICT"); + } + } + + private Record source(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + return row; + } + + private void requireCurrentFence(TargetProof target, UUID commitId) { + var current = + new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).orElseThrow(); + if (!current.commitId().equals(commitId)) + throw new IllegalStateException("POLICY_VISIBLE_FENCE_CHANGED"); + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(); + if (!retained.binding().equals(binding)) + throw new IllegalArgumentException("POLICY_COMMIT_BINDING_CONFLICT"); + } + + private void requireDraftAndUnfrozen(TargetProof target) { + var version = + dsl.fetchOne( + "SELECT version_state, is_script_only, script_patch_version, base_version_id FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + if (version == null + || !"DRAFT".equals(version.get("version_state", String.class)) + || !Boolean.FALSE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void lockAuthority(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) + throw new IllegalStateException("POLICY_CANONICAL_OWNER_AUTHORITY_UNAVAILABLE"); + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Policy writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java new file mode 100644 index 0000000000..30f1009f94 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Independent immutable readback boundary. Writes deliberately remain caller-transaction owned so + * the authenticated coordinator can compose application, visibility and publication atomically. No + * transport registration, retained-baseline initializer, terminal association or activation exists + * here. + */ +public final class RealmPolicySourceService { + private final RealmPolicySourceRepository repository; + private final TransactionTemplate read; + + public RealmPolicySourceService( + RealmPolicySourceRepository repository, PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + public Optional readSnapshot( + DraftCommitBinding.TargetProof target, UUID commitId) { + requireIndependent(); + return read.execute(status -> repository.readSnapshot(target, commitId)); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + requireIndependent(); + return read.execute(status -> repository.readCapture(operation)); + } + + public Optional readGenesis(DraftCommitBinding.TargetProof target) { + requireIndependent(); + return read.execute(status -> repository.readGenesis(target)); + } + + private static void requireIndependent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Independent immutable policy readback required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 5fb4ca04b7..99fe91853d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java @@ -50,8 +50,11 @@ public GameAsset save(GameAsset asset) { .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) .set(CREATED_AT, createdAt) - .returning() + .returning(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Inserted game asset could not be read back"); + } return toEntity(record); } dsl.update(TABLE_REF) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index ea1b7062d4..e381634a72 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -120,7 +120,27 @@ public Game findByTenantIdForUpdate(String tenantId) { .fetchOne(this::toEntity); } - /** Resolves one exact owner key and validates persisted provenance against its game row. */ + /** Reads one persisted tenant UUID and validates its provenance against the actual owner row. */ + public Optional findRuntimeTenantIdentityByCanonicalTenantId( + UUID canonicalTenantId) { + if (canonicalTenantId == null) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + return dsl.select( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .fetchOptional(this::toRuntimeTenantIdentity); + } + + /** + * Resolves the exact existing owner tenant key to its persisted canonical UUID and provenance. + */ public Optional findRuntimeTenantIdentityByTenantKey(String tenantKey) { if (tenantKey == null || tenantKey.isBlank()) { throw new IllegalArgumentException("Exact Game Design tenant key is required"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java index 4e18a44aea..3f09f54f70 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java @@ -4,6 +4,7 @@ import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import org.jooq.DSLContext; import org.jooq.Field; @@ -12,6 +13,7 @@ import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +/** Owner-local immutable launch descriptor history. */ @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -43,6 +45,31 @@ public class LaunchDescriptorRepository { DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field REMAP_SET_ID = DSL.field(DSL.name("remap_set_id"), String.class); + private static final Field DESCRIPTOR_SCHEMA_VERSION = + DSL.field(DSL.name("descriptor_schema_version"), Integer.class); + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("authored_world_source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("authored_world_source_evidence_digest"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RESULT_DIGEST = + DSL.field(DSL.name("result_digest"), String.class); + private static final Field ORIGINAL_REQUEST_JSON = + DSL.field(DSL.name("original_request_json"), String.class); + private static final Field SOURCE_EVIDENCE_JSON = + DSL.field(DSL.name("source_evidence_json"), String.class); + private static final Field OUTCOME_STATUS = + DSL.field(DSL.name("outcome_status"), String.class); + private static final Field FAILURE_CODE = + DSL.field(DSL.name("failure_code"), String.class); + private static final Field FAILURE_MESSAGE = + DSL.field(DSL.name("failure_message"), String.class); private static final Field CREATED_AT = DSL.field(DSL.name("created_at"), Timestamp.class); @@ -52,71 +79,98 @@ public LaunchDescriptorRepository(DSLContext dsl) { this.dsl = dsl; } - public Optional findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - String tenantId, Long gameTemplateId, String controlPlaneRequestId) { + /** Serializes one launch request identity before source, template, or version resolution. */ + public void lockBoundRequest(String targetNamespace, UUID canonicalTenantId, String requestId) { + String lockIdentity = canonicalTenantId + ":" + requestId; + dsl.fetch( + "select pg_advisory_xact_lock(hashtext(?), hashtext(?))", targetNamespace, lockIdentity); + } + + public Optional findBoundByRequest( + String targetNamespace, UUID canonicalTenantId, String controlPlaneRequestId) { return Optional.ofNullable( dsl.selectFrom(TABLE_REF) .where( - TENANT_ID - .eq(tenantId) - .and(GAME_TEMPLATE_ID.eq(gameTemplateId)) + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) .limit(1) .fetchOne(this::toEntity)); } + /** Reads the legacy private owner/request tuple only to deny unbound retained history. */ + public Optional findByPrivateRequest( + String tenantId, String controlPlaneRequestId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .limit(1) + .fetchOne(this::toEntity)); + } + public boolean existsByTenantIdAndVersionId(String tenantId, Long versionId) { return dsl.fetchExists(TABLE_REF, TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))); } - public LaunchDescriptor save(LaunchDescriptor descriptor) { + /** Inserts one immutable descriptor; conflicting identities can only return their stored row. */ + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + if (descriptor.getId() != null || descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException("Only a new bound launch descriptor can be inserted"); + } + if (descriptor.getOutcomeStatus() == null + || !(LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()))) { + throw new IllegalArgumentException("A known launch descriptor outcome is required"); + } LocalDateTime createdAt = descriptor.getCreatedAt() == null ? LocalDateTime.now() : descriptor.getCreatedAt(); - if (descriptor.getId() == null) { - dsl.insertInto(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + int inserted = + dsl.insertInto(TABLE_REF) + .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) + .set(TENANT_ID, descriptor.getTenantId()) + .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) + .set(REQUEST_HASH, descriptor.getRequestDigest()) + .set(VERSION_ID, descriptor.getVersionId()) + .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) + .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) + .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) + .set(REMAP_SET_ID, descriptor.getRemapSetId()) + .set(DESCRIPTOR_SCHEMA_VERSION, descriptor.getDescriptorSchemaVersion()) + .set(TARGET_NAMESPACE, descriptor.getTargetNamespace()) + .set(CANONICAL_TENANT_ID, UUID.fromString(descriptor.getCanonicalTenantId())) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_EVIDENCE_DIGEST, descriptor.getAuthoredWorldSourceEvidenceDigest()) + .set(REQUEST_DIGEST, descriptor.getRequestDigest()) + .set(RESULT_DIGEST, descriptor.getResultDigest()) + .set(ORIGINAL_REQUEST_JSON, descriptor.getOriginalRequestJson()) + .set(SOURCE_EVIDENCE_JSON, descriptor.getSourceEvidenceJson()) + .set(OUTCOME_STATUS, descriptor.getOutcomeStatus()) + .set(FAILURE_CODE, descriptor.getFailureCode()) + .set(FAILURE_MESSAGE, descriptor.getFailureMessage()) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .onConflictDoNothing() + .execute(); + Optional stored = + findBoundByRequest( + descriptor.getTargetNamespace(), + UUID.fromString(descriptor.getCanonicalTenantId()), + descriptor.getControlPlaneRequestId()); + if (stored.isEmpty()) { + throw new IllegalStateException( + "Launch descriptor identity conflicts with existing immutable history"); + } + if (inserted == 0 && stored.orElseThrow().getDescriptorSchemaVersion() == null) { + throw new IllegalStateException("An unbound launch descriptor cannot be reused canonically"); } - dsl.update(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .where(ID.eq(descriptor.getId())) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + return stored.orElseThrow(); } private LaunchDescriptor toEntity(Record record) { @@ -138,7 +192,24 @@ private LaunchDescriptor toEntity(Record record) { descriptor.setReleaseBundleId(record.get(RELEASE_BUNDLE_ID)); descriptor.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); descriptor.setRemapSetId(record.get(REMAP_SET_ID)); - Timestamp createdAt = record.get(CREATED_AT); + descriptor.setDescriptorSchemaVersion(record.get(DESCRIPTOR_SCHEMA_VERSION, Integer.class)); + descriptor.setTargetNamespace(record.get(TARGET_NAMESPACE)); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID, UUID.class); + descriptor.setCanonicalTenantId( + canonicalTenantId == null ? null : canonicalTenantId.toString()); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(record.get(SOURCE_EVIDENCE_DIGEST)); + descriptor.setRequestDigest(record.get(REQUEST_DIGEST)); + descriptor.setResultDigest(record.get(RESULT_DIGEST)); + descriptor.setOriginalRequestJson(record.get(ORIGINAL_REQUEST_JSON)); + descriptor.setSourceEvidenceJson(record.get(SOURCE_EVIDENCE_JSON)); + descriptor.setOutcomeStatus(record.get(OUTCOME_STATUS)); + descriptor.setFailureCode(record.get(FAILURE_CODE)); + descriptor.setFailureMessage(record.get(FAILURE_MESSAGE)); + Timestamp createdAt = record.get(CREATED_AT, Timestamp.class); descriptor.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return descriptor; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 51c60a2779..56947f3f70 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -8,6 +8,8 @@ import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; @@ -29,6 +31,7 @@ public class PublishAttemptRepository { private static final Field PUBLISH_TYPE = DSL.field(DSL.name("publish_type"), String.class); private static final Field STATUS = DSL.field(DSL.name("status"), String.class); + private static final Field REVISION = DSL.field(DSL.name("revision"), Long.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); @@ -61,6 +64,64 @@ public Optional findByPublishWorkflowId(String publishWorkflowId .fetchOne(this::toEntity)); } + /** The owning Game lock always precedes the exact attempt lock. */ + public Optional findByPublishWorkflowIdForUpdate(String workflow) { + Optional initial = findByPublishWorkflowId(workflow); + if (initial.isEmpty()) return initial; + dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", initial.get().getTenantId()); + return Optional.ofNullable( + dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) + .where(PUBLISH_WORKFLOW_ID.eq(workflow)) + .forUpdate() + .fetchOne(this::toEntity)); + } + + public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence + requirePublicationPending(PublishAttempt attempt) { + return new GameDesignPublicationOperationRepository(dsl) + .requirePending( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest()) + .world(); + } + + public void sealPublication(PublishAttempt attempt, boolean published) { + new GameDesignPublicationOperationRepository(dsl) + .seal( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest(), + published); + if (published) { + new RealmPolicyPublicationRepository(dsl) + .retainSealedPublished(attempt.getPublishWorkflowId()); + } + } + + public void requirePublishedOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "PUBLISHED"); + } + + public void requireNoPublicationOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "NO_PUBLICATION"); + } + + private void requireTerminalOperation(PublishAttempt attempt, String outcome) { + var result = + new GameDesignPublicationOperationRepository(dsl) + .read(attempt.getPublishWorkflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!outcome.equals(result.outcome()) + || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) + || result.operation().versionId() != attempt.getVersionId() + || !result.operation().tenantKey().equals(attempt.getTenantId())) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + } + /** * Installs a compatibility digest only once, and only on the exact legacy full-version row whose * identity was validated by the caller. @@ -88,6 +149,7 @@ public Optional backfillFullVersionRequestDigestIfAbsent( .and(VERSION_NUMBER.eq(versionNumber)); dsl.update(PUBLISH_ATTEMPT_TABLE) .set(REQUEST_DIGEST, requestDigest) + .set(REVISION, REVISION.plus(1L)) .where(fullVersionAttemptIdentity.and(REQUEST_DIGEST.isNull())) .execute(); return Optional.ofNullable( @@ -116,26 +178,50 @@ public PublishAttempt save(PublishAttempt attempt) { .set(FAILURE_MESSAGE, attempt.getFailureMessage()) .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .returning() + .returning( + ID, + TENANT_ID, + PUBLISH_WORKFLOW_ID, + PUBLISH_TYPE, + STATUS, + REVISION, + VERSION_ID, + VERSION_NUMBER, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + REQUEST_DIGEST, + FAILURE_CODE, + FAILURE_MESSAGE, + CREATED_AT, + COMPLETED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Publish attempt insert did not return its persisted row"); + } return toEntity(record); } - dsl.update(PUBLISH_ATTEMPT_TABLE) - .set(TENANT_ID, attempt.getTenantId()) - .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) - .set(PUBLISH_TYPE, attempt.getPublishType().name()) - .set(STATUS, attempt.getStatus().name()) - .set(VERSION_ID, attempt.getVersionId()) - .set(VERSION_NUMBER, attempt.getVersionNumber()) - .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) - .set(BASE_VERSION_ID, attempt.getBaseVersionId()) - .set(REQUEST_DIGEST, attempt.getRequestDigest()) - .set(FAILURE_CODE, attempt.getFailureCode()) - .set(FAILURE_MESSAGE, attempt.getFailureMessage()) - .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) - .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .where(ID.eq(attempt.getId())) - .execute(); + int changed = + dsl.update(PUBLISH_ATTEMPT_TABLE) + .set(TENANT_ID, attempt.getTenantId()) + .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) + .set(PUBLISH_TYPE, attempt.getPublishType().name()) + .set(STATUS, attempt.getStatus().name()) + .set(REVISION, Math.addExact(attempt.getRevision(), 1L)) + .set(VERSION_ID, attempt.getVersionId()) + .set(VERSION_NUMBER, attempt.getVersionNumber()) + .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) + .set(BASE_VERSION_ID, attempt.getBaseVersionId()) + .set(REQUEST_DIGEST, attempt.getRequestDigest()) + .set(FAILURE_CODE, attempt.getFailureCode()) + .set(FAILURE_MESSAGE, attempt.getFailureMessage()) + .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) + .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) + .where( + ID.eq(attempt.getId()) + .and(REVISION.eq(attempt.getRevision())) + .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) + .execute(); + if (changed != 1) throw new IllegalStateException("PUBLISH_ATTEMPT_CAS_CONFLICT"); return findByPublishWorkflowId(attempt.getPublishWorkflowId()).orElseThrow(); } @@ -145,6 +231,7 @@ private PublishAttempt toEntity(Record record) { } PublishAttempt attempt = new PublishAttempt(); attempt.setId(record.get(ID)); + attempt.setRevision(record.get(REVISION)); attempt.setTenantId(record.get(TENANT_ID)); attempt.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); String publishType = record.get(PUBLISH_TYPE); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index f57a7af717..516dfa2a06 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -1,10 +1,20 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -18,9 +28,18 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class PublishedReleaseBundleRepository { private static final Table TABLE_REF = DSL.table(DSL.name("published_release_bundle")); + private static final Table VERSION_SOURCE = + DSL.table(DSL.name("version")).as("source_version"); + private static final Table GAME_SOURCE = DSL.table(DSL.name("game")).as("source_game"); private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field ATTESTATION_SCHEMA_VERSION = @@ -29,6 +48,10 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("publish_workflow_id"), String.class); private static final Field MANIFEST_HASH = DSL.field(DSL.name("manifest_hash"), String.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); private static final Field GENERATION_CONFIG_REVISION = DSL.field(DSL.name("generation_config_revision"), String.class); private static final Field REQUIRED_MANIFEST_ASSET_KEYS_JSON = @@ -37,6 +60,8 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("participant_digests_json"), String.class); private static final Field COMMAND_DEFINITIONS_JSON = DSL.field(DSL.name("command_definitions_json"), String.class); + private static final Field WORLD_SELECTOR_EVIDENCE_JSON = + DSL.field(DSL.name("world_published_start_location_evidence_json"), String.class); private static final Field SCRIPT_ONLY = DSL.field(DSL.name("script_only"), Boolean.class); private static final Field SCRIPT_PATCH_VERSION = @@ -44,6 +69,35 @@ public class PublishedReleaseBundleRepository { private static final Field PUBLISHED_AT = DSL.field(DSL.name("published_at"), Timestamp.class); + private static final Field SOURCE_VERSION_ID = + DSL.field(DSL.name("source_version", "id"), Long.class); + private static final Field SOURCE_VERSION_TENANT_ID = + DSL.field(DSL.name("source_version", "tenant_id"), String.class); + private static final Field SOURCE_VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_version", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("source_version", "canonical_version_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_version", "identity_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_version", "identity_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_version", "identity_source_provenance_kind"), String.class); + private static final Field SOURCE_GAME_ID = + DSL.field(DSL.name("source_game", "id"), Long.class); + private static final Field SOURCE_GAME_TENANT_ID = + DSL.field(DSL.name("source_game", "tenant_id"), String.class); + private static final Field SOURCE_GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_game", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_PROVENANCE_KIND = + DSL.field(DSL.name("source_game", "tenant_identity_provenance_kind"), String.class); + private static final Field SOURCE_GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("source_game", "tenant_identity_source_game_id"), Long.class); + private static final Field SOURCE_GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("source_game", "tenant_identity_source_legacy_tenant_id"), String.class); + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; public PublishedReleaseBundleRepository(DSLContext dsl) { @@ -59,46 +113,215 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + /** + * Reads the exact full-version command snapshot frozen for the retained publication operation. + * The requested Version tuple, operation selection, World evidence, and both source captures are + * checked before a bundle producer can persist command bytes. + */ + public List requireSelectedCommandDefinitions( + String tenantId, + Long versionId, + String publishWorkflowId, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(publishWorkflowId, "publishWorkflowId"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + + GameDesignPublicationOperation operation = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .map(GameDesignPublicationOperationRepository.Readback::operation) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_OPERATION_UNAVAILABLE")); + var selection = operation.account().input().selection(); + var target = selection.target(); + if (!tenantId.equals(operation.tenantKey()) + || !versionId.equals(operation.versionId()) + || !publishWorkflowId.equals(operation.workflowId()) + || !tenantId.equals(target.gameDesignVersionTenantKey()) + || !versionId.equals(target.gameDesignVersionRowId()) + || !Arrays.equals(operation.world().canonicalBytes(), worldEvidence.canonicalBytes()) + || !target.canonicalTenantId().equals(worldEvidence.request().canonicalTenantId()) + || !target.canonicalVersionId().equals(worldEvidence.request().canonicalVersionId()) + || !publishWorkflowId.equals(worldEvidence.request().publishWorkflowId())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CONFLICT"); + } + + GameDesignSourceRepository.Capture capture = + new GameDesignSourceRepository(dsl) + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + if (!Arrays.equals( + capture.command().operation().canonicalBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("SELECTED_COMMAND_CAPTURE_OPERATION_CONFLICT"); + } + return capture.command().snapshot().definitions().stream() + .map(CommandSource.Definition::definitionJson) + .toList(); + } + public PublishedReleaseBundle save(PublishedReleaseBundle bundle) { - LocalDateTime publishedAt = - bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); - if (bundle.getId() == null) { - Long generatedId = - dsl.insertInto(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .returningResult(ID) - .fetchOne(ID); - return dsl.selectFrom(TABLE_REF).where(ID.eq(generatedId)).fetchOne(this::toEntity); + Objects.requireNonNull(bundle, "bundle"); + if (bundle.getId() != null) { + throw new IllegalStateException( + "Published release bundle is immutable; read the stored row instead of saving it again"); + } + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + LocalDateTime publishedAt = + bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); + return insertNewBundle(tx, bundle, publishedAt); + }); + } + + private PublishedReleaseBundle insertNewBundle( + DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { + CanonicalSource source = findExactCanonicalSource(tx, bundle); + rejectCallerIdentitySubstitution(bundle, source); + verifySelectorSource(bundle, source); + if ("v2".equals(bundle.getAttestationSchemaVersion())) { + PublishedReleaseBundle existing = + tx.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) + .fetchOne(this::toEntity); + if (existing != null) { + try { + verifyPersistedSource(existing, bundle, source, existing.getPublishedReleaseBundleRef()); + } catch (IllegalStateException conflict) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input", conflict); + } + return existing; + } } - dsl.update(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .where(ID.eq(bundle.getId())) - .execute(); - return findByTenantIdAndVersionId(bundle.getTenantId(), bundle.getVersionId()).orElseThrow(); + String publishedReleaseBundleRef = UUID.randomUUID().toString(); + + Long generatedId = + tx.insertInto(TABLE_REF) + .set(PUBLISHED_RELEASE_BUNDLE_REF, publishedReleaseBundleRef) + .set(TENANT_ID, bundle.getTenantId()) + .set(VERSION_ID, bundle.getVersionId()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, source.canonicalVersionId()) + .set(VERSION_NUMBER, bundle.getVersionNumber()) + .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) + .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) + .set(MANIFEST_HASH, bundle.getManifestHash()) + .set(MANIFEST_SCHEMA_VERSION, bundle.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, bundle.getArtifactDigestsJson()) + .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) + .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) + .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) + .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) + .set(WORLD_SELECTOR_EVIDENCE_JSON, bundle.getWorldPublishedStartLocationEvidenceJson()) + .set(SCRIPT_ONLY, bundle.isScriptOnly()) + .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) + .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) + .returningResult(ID) + .fetchOne(ID); + if (generatedId == null) { + throw new IllegalStateException("Published release bundle insert returned no row id"); + } + + PublishedReleaseBundle persisted = findById(tx, generatedId).orElseThrow(); + verifyPersistedSource(persisted, bundle, source, publishedReleaseBundleRef); + return persisted; + } + + private CanonicalSource findExactCanonicalSource(DSLContext tx, PublishedReleaseBundle bundle) { + if (bundle.getTenantId() == null || bundle.getVersionId() == null) { + throw new IllegalArgumentException( + "Published release bundle requires tenant and Version row"); + } + + Record source = + tx.select(SOURCE_VERSION_CANONICAL_TENANT_ID, SOURCE_VERSION_CANONICAL_VERSION_ID) + .from(VERSION_SOURCE.join(GAME_SOURCE).on(SOURCE_GAME_ROW_ID.eq(SOURCE_GAME_ID))) + .where( + SOURCE_VERSION_ID + .eq(bundle.getVersionId()) + .and(SOURCE_VERSION_TENANT_ID.eq(bundle.getTenantId())) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_TENANT_ID.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_GAME_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.eq(SOURCE_GAME_CANONICAL_TENANT_ID)) + .and(SOURCE_PROVENANCE_KIND.eq(SOURCE_GAME_PROVENANCE_KIND)) + .and(SOURCE_PROVENANCE_KIND.in("NEW_GAME_ROW", "RETAINED_GAME_V29")) + .and(SOURCE_GAME_SOURCE_ROW_ID.eq(SOURCE_GAME_ID)) + .and(SOURCE_GAME_SOURCE_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID))) + .forUpdate() + .fetchOne(); + if (source == null) { + throw new IllegalStateException( + "No exact canonical Game Design source association exists for the requested Version"); + } + + UUID canonicalTenantId = source.get(SOURCE_VERSION_CANONICAL_TENANT_ID); + UUID canonicalVersionId = source.get(SOURCE_VERSION_CANONICAL_VERSION_ID); + if (canonicalTenantId == null + || NIL_UUID.equals(canonicalTenantId) + || canonicalVersionId == null + || NIL_UUID.equals(canonicalVersionId)) { + throw new IllegalStateException("Exact Game Design source has an invalid canonical identity"); + } + return new CanonicalSource(canonicalTenantId, canonicalVersionId); + } + + private void rejectCallerIdentitySubstitution( + PublishedReleaseBundle bundle, CanonicalSource source) { + if ((bundle.getCanonicalTenantId() != null + && !bundle.getCanonicalTenantId().equals(source.canonicalTenantId())) + || (bundle.getCanonicalVersionId() != null + && !bundle.getCanonicalVersionId().equals(source.canonicalVersionId()))) { + throw new IllegalArgumentException( + "Caller-supplied canonical release identity does not match the exact Version source"); + } + } + + private void verifyPersistedSource( + PublishedReleaseBundle persisted, + PublishedReleaseBundle requested, + CanonicalSource source, + String publishedReleaseBundleRef) { + if (!Objects.equals(persisted.getTenantId(), requested.getTenantId()) + || !Objects.equals(persisted.getVersionId(), requested.getVersionId()) + || !Objects.equals(persisted.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId()) + || !Objects.equals(persisted.getManifestHash(), requested.getManifestHash()) + || !Objects.equals( + persisted.getManifestSchemaVersion(), requested.getManifestSchemaVersion()) + || !Objects.equals(persisted.getArtifactDigestsJson(), requested.getArtifactDigestsJson()) + || !Objects.equals( + persisted.getWorldPublishedStartLocationEvidenceJson(), + requested.getWorldPublishedStartLocationEvidenceJson()) + || !Objects.equals( + persisted.getAttestationSchemaVersion(), requested.getAttestationSchemaVersion()) + || !Objects.equals(persisted.getPublishWorkflowId(), requested.getPublishWorkflowId()) + || persisted.getVersionNumber() != requested.getVersionNumber() + || !Objects.equals( + persisted.getGenerationConfigRevision(), requested.getGenerationConfigRevision()) + || !Objects.equals( + persisted.getCommandDefinitionsJson(), requested.getCommandDefinitionsJson()) + || persisted.isScriptOnly() != requested.isScriptOnly() + || !Objects.equals(persisted.getScriptPatchVersion(), requested.getScriptPatchVersion()) + || !Objects.equals( + persisted.getRequiredManifestAssetKeysJson(), + requested.getRequiredManifestAssetKeysJson()) + || !Objects.equals( + persisted.getParticipantDigestsJson(), requested.getParticipantDigestsJson()) + || !Objects.equals(persisted.getPublishedReleaseBundleRef(), publishedReleaseBundleRef)) { + throw new IllegalStateException( + "Published release bundle readback does not match its source identity and owner reference"); + } + } + + private Optional findById(DSLContext tx, Long id) { + return Optional.ofNullable(tx.selectFrom(TABLE_REF).where(ID.eq(id)).fetchOne(this::toEntity)); } private PublishedReleaseBundle toEntity(Record record) { @@ -107,20 +330,53 @@ private PublishedReleaseBundle toEntity(Record record) { } PublishedReleaseBundle bundle = new PublishedReleaseBundle(); bundle.setId(record.get(ID)); + bundle.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); bundle.setTenantId(record.get(TENANT_ID)); bundle.setVersionId(record.get(VERSION_ID)); + bundle.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + bundle.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); bundle.setVersionNumber(record.get(VERSION_NUMBER)); bundle.setAttestationSchemaVersion(record.get(ATTESTATION_SCHEMA_VERSION)); bundle.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); bundle.setManifestHash(record.get(MANIFEST_HASH)); + bundle.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + bundle.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); bundle.setGenerationConfigRevision(record.get(GENERATION_CONFIG_REVISION)); bundle.setRequiredManifestAssetKeysJson(record.get(REQUIRED_MANIFEST_ASSET_KEYS_JSON)); bundle.setParticipantDigestsJson(record.get(PARTICIPANT_DIGESTS_JSON)); bundle.setCommandDefinitionsJson(record.get(COMMAND_DEFINITIONS_JSON)); + bundle.setWorldPublishedStartLocationEvidenceJson(record.get(WORLD_SELECTOR_EVIDENCE_JSON)); bundle.setScriptOnly(Boolean.TRUE.equals(record.get(SCRIPT_ONLY))); bundle.setScriptPatchVersion(record.get(SCRIPT_PATCH_VERSION)); Timestamp publishedAt = record.get(PUBLISHED_AT); bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); + verifySelectorSource( + bundle, new CanonicalSource(bundle.getCanonicalTenantId(), bundle.getCanonicalVersionId())); return bundle; } + + private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) { + String bytes = bundle.getWorldPublishedStartLocationEvidenceJson(); + if (!"v2".equals(bundle.getAttestationSchemaVersion())) { + if (bytes != null) { + throw new IllegalArgumentException( + "Selector evidence is forbidden on historical release schemas"); + } + return; + } + if (bytes == null) { + throw new IllegalArgumentException("World selector evidence is mandatory for release v2"); + } + var request = + WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8)) + .request(); + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.canonicalVersionId().equals(source.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "World selector differs from exact Version source/workflow"); + } + } + + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java index c92f1271b1..049fb6fb61 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java @@ -40,6 +40,14 @@ public class VersionAssetArtifactRepository { DSL.field(DSL.name("exported_manifest_asset_keys_json"), String.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); + private static final Field PUBLISHED_OBJECT_PROOFS_JSON = + DSL.field(DSL.name("published_object_proofs_json"), String.class); + private static final Field CANDIDATE_SNAPSHOT_VERSION_ID = + DSL.field(DSL.name("candidate_snapshot_version_id"), Long.class); private final DSLContext dsl; @@ -56,6 +64,15 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + public Optional findByTenantIdAndVersionIdForUpdate( + String tenantId, Long versionId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))) + .forUpdate() + .fetchOne(this::toEntity)); + } + public VersionAssetArtifact save(VersionAssetArtifact artifact) { LocalDateTime updatedAt = artifact.getUpdatedAt() == null ? LocalDateTime.now() : artifact.getUpdatedAt(); @@ -72,6 +89,10 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) .returning(ID) .fetchOne(); @@ -84,20 +105,35 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .orElseThrow( () -> new IllegalStateException("VERSION_ASSET_ARTIFACT_INSERT_READBACK_FAILED")); } - dsl.update(TABLE_REF) - .set(TENANT_ID, artifact.getTenantId()) - .set(VERSION_ID, artifact.getVersionId()) - .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) - .set(ARTIFACT_STATE, artifact.getArtifactState().name()) - .set(STATE_EPOCH, artifact.getStateEpoch()) - .set(MANIFEST_HASH, artifact.getManifestHash()) - .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) - .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) - .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) - .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) - .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) - .where(ID.eq(artifact.getId())) - .execute(); + if (artifact.getStateEpoch() <= 0) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } + int updated = + dsl.update(TABLE_REF) + .set(TENANT_ID, artifact.getTenantId()) + .set(VERSION_ID, artifact.getVersionId()) + .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) + .set(ARTIFACT_STATE, artifact.getArtifactState().name()) + .set(STATE_EPOCH, artifact.getStateEpoch()) + .set(MANIFEST_HASH, artifact.getManifestHash()) + .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) + .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) + .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) + .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) + .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) + .where( + ID.eq(artifact.getId()) + .and(TENANT_ID.eq(artifact.getTenantId())) + .and(VERSION_ID.eq(artifact.getVersionId())) + .and(STATE_EPOCH.eq(artifact.getStateEpoch() - 1))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } return findByTenantIdAndVersionId(artifact.getTenantId(), artifact.getVersionId()) .orElseThrow(); } @@ -120,6 +156,10 @@ private VersionAssetArtifact toEntity(Record record) { artifact.setLastErrorCode(record.get(LAST_ERROR_CODE)); artifact.setLastErrorMessage(record.get(LAST_ERROR_MESSAGE)); artifact.setExportedManifestAssetKeysJson(record.get(EXPORTED_MANIFEST_ASSET_KEYS_JSON)); + artifact.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + artifact.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); + artifact.setPublishedObjectProofsJson(record.get(PUBLISHED_OBJECT_PROOFS_JSON)); + artifact.setCandidateSnapshotVersionId(record.get(CANDIDATE_SNAPSHOT_VERSION_ID)); artifact.setUpdatedAt(JooqPersistenceSupport.toLocalDateTime(record.get(UPDATED_AT))); return artifact; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java new file mode 100644 index 0000000000..de00d10285 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -0,0 +1,570 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Owner-local persistence boundary for Draft asset mappings and durable export snapshots. */ +@Repository +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects a missing DSLContext before publication; this repository has no finalizer") +public class VersionAssetPublicationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator UTF8_BYTE_ORDER = + VersionAssetPublicationRepository::compareUtf8; + + private final DSLContext dsl; + + public VersionAssetPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in + * this method are private Game Design owner keys and are not public identity aliases. + */ + public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireTenantId(tenantId); + if (versionId <= 0 || assetId <= 0) { + throw new IllegalArgumentException("Version and asset owner keys must be positive"); + } + + VersionRow version = + lockVersionByTenantAndId(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version row was not found")); + qualifyVersion(version); + requireDraft(version); + requireNoSnapshot(tenantId, versionId); + + AssetRow asset = + findAssetForUpdate(tenantId, assetId) + .orElseThrow( + () -> new IllegalStateException("Exact tenant game asset row was not found")); + validateUsageKey(asset.fileName()); + + Record existing = + dsl.fetchOne( + "SELECT usage_key, usage_type FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND asset_id = ?", + tenantId, + versionId, + assetId); + if (existing != null) { + if (Objects.equals(existing.get("usage_key", String.class), asset.fileName()) + && Objects.equals(existing.get("usage_type", String.class), usageType)) { + return; + } + throw new IllegalStateException("Conflicting Version asset association already exists"); + } + + Record usageCollision = + dsl.fetchOne( + "SELECT asset_id FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND usage_key = ?", + tenantId, + versionId, + asset.fileName()); + if (usageCollision != null) { + throw new IllegalStateException("Version asset usage key is already mapped to another asset"); + } + + dsl.execute( + "INSERT INTO version_asset " + + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", + tenantId, + versionId, + assetId, + asset.fileName(), + usageType); + } + + /** + * Freezes the current exact Draft mapping set or reads an earlier frozen snapshot. The caller + * must hold a transaction because the Version lock serializes mapping writes with first freeze. + */ + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + lockVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + + if (hasSnapshot(tenantId, version.id())) { + return readSnapshot(version); + } + requireDraft(version); + + List selected = lockMappedSourceAssets(tenantId, version.id()); + selected.sort(Comparator.comparing(asset -> asset.usageKey(), UTF8_BYTE_ORDER)); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + List prepared = new ArrayList<>(selected.size()); + for (SourceAsset source : selected) { + validateUsageKey(source.usageKey()); + if (source.assetId() == null) { + throw new IllegalStateException("Version asset source row identity is missing"); + } + if (!Objects.equals(source.usageKey(), source.fileName())) { + throw new IllegalStateException( + "Version asset usage key no longer matches its source file name"); + } + if (!usageKeys.add(source.usageKey()) || !assetIds.add(source.assetId())) { + throw new IllegalStateException( + "Version asset mapping contains a duplicate source or usage key"); + } + byte[] bytes = requireBytes(source.bytes()); + prepared.add( + new PreparedAsset( + source.usageKey(), + source.assetId(), + requireContentType(source.contentType()), + bytes, + digest(bytes))); + } + + for (PreparedAsset asset : prepared) { + dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + asset.usageKey(), + asset.assetId(), + asset.contentType(), + asset.contentDigest(), + (long) asset.bytes().length); + } + dsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + version.canonicalTenantId(), + version.canonicalVersionId(), + version.versionNumber(), + version.stateEpoch(), + prepared.size()); + + return readSnapshot(version); + } + + /** + * Reads only an already committed owner-local snapshot; absence is never interpreted as empty. + */ + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + readVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + return readSnapshot(version); + } + + private ExportSnapshot readSnapshot(VersionRow version) { + Record header = + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count " + + "FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id()); + if (header == null) { + throw new IllegalStateException("No durable frozen Version asset snapshot exists"); + } + + UUID canonicalTenantId = header.get("canonical_tenant_id", UUID.class); + UUID canonicalVersionId = header.get("canonical_version_id", UUID.class); + Integer storedVersionNumber = header.get("version_number", Integer.class); + Long capturedEpoch = header.get("captured_version_state_epoch", Long.class); + Integer itemCount = header.get("item_count", Integer.class); + if (!Objects.equals(canonicalTenantId, version.canonicalTenantId()) + || !Objects.equals(canonicalVersionId, version.canonicalVersionId()) + || !Objects.equals(storedVersionNumber, version.versionNumber()) + || capturedEpoch == null + || capturedEpoch <= 0 + || version.stateEpoch() < capturedEpoch + || itemCount == null + || itemCount < 0) { + throw new IllegalStateException("Frozen Version asset snapshot identity is inconsistent"); + } + + long mappingCount = + Optional.ofNullable( + dsl.fetchOne( + "SELECT count(*) AS item_count FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id())) + .map(row -> row.get("item_count", Long.class)) + .orElse(0L); + if (mappingCount != itemCount.longValue()) { + throw new IllegalStateException( + "Frozen snapshot no longer matches its complete Version mapping set"); + } + + List rows = + dsl.fetch( + "SELECT i.usage_key AS snapshot_usage_key, i.asset_id AS snapshot_asset_id, " + + "i.content_type AS snapshot_content_type, i.content_hash AS snapshot_content_hash, " + + "i.byte_size AS snapshot_byte_size, va.usage_key AS mapping_usage_key, " + + "va.asset_id AS mapping_asset_id, ga.id AS source_asset_id, " + + "ga.tenant_id AS source_tenant_id, ga.file_name AS source_file_name, " + + "ga.content_type AS source_content_type, ga.data AS source_data " + + "FROM version_asset_export_item i " + + "LEFT JOIN version_asset va ON va.tenant_id = i.tenant_id " + + "AND va.version_id = i.version_id AND va.asset_id = i.asset_id " + + "AND va.usage_key = i.usage_key " + + "LEFT JOIN game_assets ga ON ga.tenant_id = i.tenant_id AND ga.id = i.asset_id " + + "WHERE i.tenant_id = ? AND i.version_id = ?", + version.tenantId(), + version.id()); + if (rows.size() != itemCount) { + throw new IllegalStateException("Frozen Version asset snapshot is incomplete"); + } + + List items = new ArrayList<>(rows.size()); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + for (Record row : rows) { + String usageKey = row.get("snapshot_usage_key", String.class); + Long snapshotAssetId = row.get("snapshot_asset_id", Long.class); + String snapshotType = row.get("snapshot_content_type", String.class); + String snapshotDigest = row.get("snapshot_content_hash", String.class); + Long snapshotSize = row.get("snapshot_byte_size", Long.class); + Long mappingAssetId = row.get("mapping_asset_id", Long.class); + String mappingUsageKey = row.get("mapping_usage_key", String.class); + Long sourceAssetId = row.get("source_asset_id", Long.class); + String sourceTenantId = row.get("source_tenant_id", String.class); + String sourceFileName = row.get("source_file_name", String.class); + String sourceType = row.get("source_content_type", String.class); + byte[] sourceData = row.get("source_data", byte[].class); + + validateUsageKey(usageKey); + requireContentType(sourceType); + if (snapshotAssetId == null + || snapshotType == null + || snapshotDigest == null + || snapshotSize == null + || !snapshotAssetId.equals(mappingAssetId) + || !Objects.equals(usageKey, mappingUsageKey) + || !snapshotAssetId.equals(sourceAssetId) + || !Objects.equals(version.tenantId(), sourceTenantId) + || !Objects.equals(usageKey, sourceFileName) + || !Objects.equals(snapshotType, sourceType) + || sourceData == null + || snapshotSize != sourceData.length + || !snapshotDigest.equals(digest(sourceData))) { + throw new IllegalStateException( + "Frozen Version asset source bytes or mapping failed verification"); + } + if (!usageKeys.add(usageKey) || !assetIds.add(snapshotAssetId)) { + throw new IllegalStateException( + "Frozen Version asset snapshot contains duplicate keys or sources"); + } + items.add( + new AssetSelection(usageKey, snapshotAssetId, sourceData, sourceType, snapshotDigest)); + } + items.sort(Comparator.comparing(AssetSelection::usageKey, UTF8_BYTE_ORDER)); + + return new ExportSnapshot( + version.tenantId(), + version.id(), + storedVersionNumber, + capturedEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private List lockMappedSourceAssets(String tenantId, long versionId) { + return dsl.fetch( + "SELECT va.usage_key, va.asset_id, ga.file_name, ga.content_type, ga.data " + + "FROM version_asset va " + + "JOIN game_assets ga ON ga.tenant_id = va.tenant_id AND ga.id = va.asset_id " + + "AND ga.file_name = va.usage_key " + + "WHERE va.tenant_id = ? AND va.version_id = ? " + + "ORDER BY va.asset_id FOR UPDATE OF ga", + tenantId, + versionId) + .map( + row -> + new SourceAsset( + row.get("usage_key", String.class), + row.get("asset_id", Long.class), + row.get("file_name", String.class), + row.get("content_type", String.class), + row.get("data", byte[].class))); + } + + private Optional findAssetForUpdate(String tenantId, long assetId) { + Record row = + dsl.fetchOne( + "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + assetId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(new AssetRow(row.get("file_name", String.class))); + } + + private Optional lockVersionByTenantAndId(String tenantId, long versionId) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + versionId); + } + + private Optional lockVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ? FOR UPDATE", + tenantId, + versionNumber); + } + + private Optional readVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ?", + tenantId, + versionNumber); + } + + private Optional readVersion(String sql, Object first, Object second) { + Record row = dsl.fetchOne(sql, first, second); + if (row == null) { + return Optional.empty(); + } + return Optional.of( + new VersionRow( + row.get("id", Long.class), + row.get("tenant_id", String.class), + row.get("version_number", Integer.class), + row.get("version_state", String.class), + row.get("version_state_epoch", Long.class), + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class))); + } + + private void qualifyVersion(VersionRow version) { + if (version.id() == null + || version.id() <= 0 + || version.tenantId() == null + || version.versionNumber() == null + || version.versionNumber() <= 0 + || version.stateEpoch() == null + || version.stateEpoch() <= 0 + || version.canonicalTenantId() == null + || version.canonicalVersionId() == null + || NIL_UUID.equals(version.canonicalTenantId()) + || NIL_UUID.equals(version.canonicalVersionId()) + || version.identitySourceGameRowId() == null + || version.identitySourceGameRowId() <= 0 + || !Objects.equals(version.tenantId(), version.identitySourceGameTenantKey()) + || !("NEW_GAME_ROW".equals(version.identitySourceProvenanceKind()) + || "RETAINED_GAME_V29".equals(version.identitySourceProvenanceKind()))) { + throw new IllegalStateException("Version lacks a complete canonical owner identity"); + } + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE id = ? AND tenant_id = ?", + version.identitySourceGameRowId(), + version.identitySourceGameTenantKey()); + if (game == null + || !Objects.equals(game.get("canonical_tenant_id", UUID.class), version.canonicalTenantId()) + || !Objects.equals( + game.get("tenant_identity_provenance_kind", String.class), + version.identitySourceProvenanceKind()) + || !Objects.equals( + game.get("tenant_identity_source_game_id", Long.class), game.get("id", Long.class)) + || !Objects.equals( + game.get("tenant_identity_source_legacy_tenant_id", String.class), + version.tenantId())) { + throw new IllegalStateException( + "Version canonical identity does not match its exact source Game row"); + } + if (version.state() == null) { + throw new IllegalStateException("Version has an unexpected lifecycle state"); + } + try { + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.valueOf(version.state()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Version has an unexpected lifecycle state", exception); + } + } + + private void requireDraft(VersionRow version) { + if (!"DRAFT".equals(version.state())) { + throw new IllegalStateException( + "Version asset mappings and first freeze require a Draft Version"); + } + } + + private void requireNoSnapshot(String tenantId, long versionId) { + if (hasSnapshot(tenantId, versionId)) { + throw new IllegalStateException( + "Version asset mappings are frozen by the durable export snapshot"); + } + } + + private boolean hasSnapshot(String tenantId, long versionId) { + return dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId) + != null; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } + + private static void validateUsageKey(String usageKey) { + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException("Asset source file name cannot be a blank usage key"); + } + if ("manifest.json".equals(usageKey)) { + throw new IllegalStateException( + "Asset source file name collides with the reserved manifest.json key"); + } + } + + private static String requireContentType(String contentType) { + if (contentType == null || contentType.isBlank()) { + throw new IllegalStateException("Asset source content type is missing"); + } + return contentType; + } + + private static byte[] requireBytes(byte[] bytes) { + if (bytes == null) { + throw new IllegalStateException("Asset source bytes are missing"); + } + return bytes.clone(); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is not available", exception); + } + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int compared = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (compared != 0) { + return compared; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private record VersionRow( + Long id, + String tenantId, + Integer versionNumber, + String state, + Long stateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long identitySourceGameRowId, + String identitySourceGameTenantKey, + String identitySourceProvenanceKind) {} + + private record AssetRow(String fileName) {} + + private record SourceAsset( + String usageKey, Long assetId, String fileName, String contentType, byte[] bytes) {} + + private record PreparedAsset( + String usageKey, long assetId, String contentType, byte[] bytes, String contentDigest) {} + + /** + * A defensive byte selection persisted in the immutable per-Version export projection. The + * numeric asset id is a private Game Design owner key, not an external identifier. + */ + public record AssetSelection( + String usageKey, long assetId, byte[] bytes, String contentType, String contentDigest) { + public AssetSelection { + Objects.requireNonNull(usageKey, "usageKey"); + Objects.requireNonNull(bytes, "bytes"); + Objects.requireNonNull(contentType, "contentType"); + Objects.requireNonNull(contentDigest, "contentDigest"); + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + /** + * Complete owner-local immutable readback for a frozen Version asset selection. Its tenant, + * Version, and asset numeric ids remain private owner keys; canonical UUIDs are read from + * persisted provenance and do not alias those keys. + */ + public record ExportSnapshot( + String tenantId, + long versionId, + int versionNumber, + long capturedVersionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + public ExportSnapshot { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + items = List.copyOf(Objects.requireNonNull(items, "items")); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 8177e4b751..c74a4f5da5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -6,14 +6,21 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -21,8 +28,40 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class VersionRepository { private static final Table VERSION_TABLE = DSL.table(DSL.name("version")); + private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("version", "tenant_id"), String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("version", "canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("version", "identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("version", "identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("version", "identity_source_provenance_kind"), String.class); + private static final Field GAME_ID = DSL.field(DSL.name("game", "id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("game", "tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("game", "canonical_tenant_id"), UUID.class); + private static final Field GAME_TENANT_PROVENANCE_KIND = + DSL.field(DSL.name("game", "tenant_identity_provenance_kind"), String.class); + private static final Field GAME_TENANT_SOURCE_GAME_ID = + DSL.field(DSL.name("game", "tenant_identity_source_game_id"), Long.class); + private static final Field GAME_TENANT_SOURCE_LEGACY_KEY = + DSL.field(DSL.name("game", "tenant_identity_source_legacy_tenant_id"), String.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field VERSION_STATE = @@ -40,6 +79,7 @@ public class VersionRepository { DSL.field(DSL.name("created_at"), Timestamp.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; @@ -79,6 +119,56 @@ public Optional findByTenantIdAndId(String tenantId, Long id) { .fetchOne(this::toEntity)); } + /** Reads and locks the exact version row for owner-local guarded lifecycle writes. */ + public Optional findByTenantIdAndIdForUpdate(String tenantId, Long id) { + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where(TENANT_ID.eq(tenantId).and(ID.eq(id))) + .forUpdate() + .fetchOne(this::toEntity)); + } + + /** + * Resolves only a canonical version UUID whose persisted tenant/source provenance still matches + * the exact Game Design owner row. Numeric Version IDs remain private to owner-local callers. + */ + public Optional findByCanonicalTenantIdAndCanonicalVersionId( + UUID canonicalTenantId, UUID canonicalVersionId) { + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(NIL_UUID) + || canonicalVersionId.equals(NIL_UUID)) { + return Optional.empty(); + } + + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where( + CANONICAL_VERSION_ID + .eq(canonicalVersionId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and( + DSL.exists( + DSL.selectOne() + .from(GAME_TABLE) + .where( + GAME_ID + .eq(VERSION_IDENTITY_SOURCE_GAME_ROW_ID) + .and( + GAME_TENANT_ID.eq( + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + .and(GAME_TENANT_ID.eq(VERSION_TENANT_ID)) + .and( + GAME_CANONICAL_TENANT_ID.eq( + VERSION_CANONICAL_TENANT_ID)) + .and( + GAME_TENANT_PROVENANCE_KIND.eq( + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND)) + .and(GAME_TENANT_SOURCE_GAME_ID.eq(GAME_ID)) + .and(GAME_TENANT_SOURCE_LEGACY_KEY.eq(GAME_TENANT_ID)))))) + .fetchOne(this::toEntity)); + } + /** * Returns every retained publication metadata candidate for an exact tenant/base/patch scope. * Callers reject anything other than one row so missing or duplicate retained scope is @@ -135,16 +225,36 @@ public long count() { return dsl.fetchCount(VERSION_TABLE); } + @Transactional(isolation = Isolation.READ_COMMITTED) public Version save(Version version) { + if (version.getId() == null + && version.getVersionState() == VersionLifecycleState.DRAFT + && !version.isScriptOnly() + && version.getBaseVersionId() == null + && version.getScriptPatchVersion() == null + && (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()))) { + throw new IllegalStateException( + "New full Draft creation requires one writable READ_COMMITTED source transaction"); + } LocalDateTime createdAt = version.getCreatedAt() == null ? LocalDateTime.now() : version.getCreatedAt(); LocalDateTime updatedAt = version.getUpdatedAt() == null ? LocalDateTime.now() : version.getUpdatedAt(); if (version.getId() == null) { + VersionSource source = findExactGameSource(version.getTenantId()); + UUID canonicalVersionId = newNonNilUuid(); Record record = Objects.requireNonNull( dsl.insertInto(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) + .set(CANONICAL_VERSION_ID, canonicalVersionId) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, source.provenanceKind()) .set(VERSION_NUMBER, version.getVersionNumber()) .set(VERSION_STATE, version.getVersionState().name()) .set(VERSION_STATE_EPOCH, version.getVersionStateEpoch()) @@ -157,6 +267,11 @@ public Version save(Version version) { .returning( ID, TENANT_ID, + CANONICAL_VERSION_ID, + CANONICAL_TENANT_ID, + IDENTITY_SOURCE_GAME_ROW_ID, + IDENTITY_SOURCE_GAME_TENANT_KEY, + IDENTITY_SOURCE_PROVENANCE_KIND, VERSION_NUMBER, VERSION_STATE, VERSION_STATE_EPOCH, @@ -167,7 +282,25 @@ public Version save(Version version) { CREATED_AT, UPDATED_AT) .fetchOne()); - return toEntity(record); + Version inserted = toEntity(record); + Version persisted = findById(inserted.getId()).orElseThrow(); + requireIssuedIdentityReadback(persisted, inserted.getTenantId(), canonicalVersionId, source); + if (persisted.getVersionState() == VersionLifecycleState.DRAFT + && !persisted.isScriptOnly() + && persisted.getBaseVersionId() == null + && persisted.getScriptPatchVersion() == null) { + new GameDesignSourceRepository(dsl) + .enrollFreshDraft( + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind())); + } + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -195,6 +328,11 @@ private Version toEntity(Record record) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + version.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); + version.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + version.setIdentitySourceGameRowId(record.get(IDENTITY_SOURCE_GAME_ROW_ID)); + version.setIdentitySourceGameTenantKey(record.get(IDENTITY_SOURCE_GAME_TENANT_KEY)); + version.setIdentitySourceProvenanceKind(record.get(IDENTITY_SOURCE_PROVENANCE_KIND)); version.setVersionNumber(record.get(VERSION_NUMBER)); String versionState = record.get(VERSION_STATE); version.setVersionState( @@ -212,4 +350,74 @@ private Version toEntity(Record record) { version.setUpdatedAt(updatedAt == null ? null : updatedAt.toLocalDateTime()); return version; } + + private VersionSource findExactGameSource(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalStateException( + "New Version requires an exact Game Design source tenant key"); + } + Record source = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_TENANT_PROVENANCE_KIND, + GAME_TENANT_SOURCE_GAME_ID, + GAME_TENANT_SOURCE_LEGACY_KEY) + .from(GAME_TABLE) + .where(GAME_TENANT_ID.eq(tenantId)) + .fetchOne(); + if (source == null) { + throw new IllegalStateException("New Version tenant has no exact Game Design source row"); + } + + Long sourceGameRowId = source.get(GAME_ID); + String sourceGameTenantKey = source.get(GAME_TENANT_ID); + UUID canonicalTenantId = source.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = source.get(GAME_TENANT_PROVENANCE_KIND); + Long tenantSourceGameRowId = source.get(GAME_TENANT_SOURCE_GAME_ID); + String tenantSourceGameTenantKey = source.get(GAME_TENANT_SOURCE_LEGACY_KEY); + if (sourceGameRowId == null + || sourceGameRowId <= 0 + || !tenantId.equals(sourceGameTenantKey) + || canonicalTenantId == null + || canonicalTenantId.equals(NIL_UUID) + || provenanceKind == null + || !("NEW_GAME_ROW".equals(provenanceKind) || "RETAINED_GAME_V29".equals(provenanceKind)) + || !sourceGameRowId.equals(tenantSourceGameRowId) + || !tenantId.equals(tenantSourceGameTenantKey)) { + throw new IllegalStateException( + "New Version tenant source provenance is incomplete or invalid"); + } + return new VersionSource( + canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind); + } + + private void requireIssuedIdentityReadback( + Version persisted, String requestedTenantKey, UUID canonicalVersionId, VersionSource source) { + if (persisted.getId() == null + || persisted.getId() <= 0 + || !requestedTenantKey.equals(persisted.getTenantId()) + || !canonicalVersionId.equals(persisted.getCanonicalVersionId()) + || !source.canonicalTenantId().equals(persisted.getCanonicalTenantId()) + || !source.sourceGameRowId().equals(persisted.getIdentitySourceGameRowId()) + || !source.sourceGameTenantKey().equals(persisted.getIdentitySourceGameTenantKey()) + || !source.provenanceKind().equals(persisted.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("Persisted Version identity did not match owner issuance"); + } + } + + private UUID newNonNilUuid() { + UUID uuid; + do { + uuid = UUID.randomUUID(); + } while (NIL_UUID.equals(uuid)); + return uuid; + } + + private record VersionSource( + UUID canonicalTenantId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java index 8408f36f1c..6980356347 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java @@ -1,15 +1,38 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import java.util.Objects; -public record ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { +/** Immutable result of constructing and verifying a version-scoped asset manifest. */ +public record ExportedAssetManifest( + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests) { public ExportedAssetManifest { - requiredManifestAssetKeys = - requiredManifestAssetKeys == null ? List.of() : List.copyOf(requiredManifestAssetKeys); - } + if (manifestHash == null || !manifestHash.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "manifestHash must be a sha256-prefixed lowercase SHA-256 digest"); + } + if (manifestSchemaVersion <= 0) { + throw new IllegalArgumentException("manifestSchemaVersion must be positive"); + } + requiredManifestAssetKeys = List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys)); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests)); - @Override - public List requiredManifestAssetKeys() { - return requiredManifestAssetKeys; + List digestUsageKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + if (!requiredManifestAssetKeys.equals(digestUsageKeys)) { + throw new IllegalArgumentException( + "required manifest keys must exactly match the ordered artifact digest usage keys"); + } + for (int index = 1; index < requiredManifestAssetKeys.size(); index++) { + if (PublishedArtifactDigest.compareUsageKeysUtf8( + requiredManifestAssetKeys.get(index - 1), requiredManifestAssetKeys.get(index)) + >= 0) { + throw new IllegalArgumentException( + "manifest asset keys must be unique and in UTF-8 byte order"); + } + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java new file mode 100644 index 0000000000..515197a302 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** Mandatory actual-byte proof for one immutable published asset object. */ +public record PublishedArtifactDigest( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + private static final String SHA256_PREFIX = "sha256:"; + + public PublishedArtifactDigest { + requireCanonicalText(usageKey, "usageKey"); + requireCanonicalText(artifactKind, "artifactKind"); + requireCanonicalText(contentType, "contentType"); + if (artifactSchemaVersion <= 0) { + throw new IllegalArgumentException("artifactSchemaVersion must be positive"); + } + if (contentDigest == null || !contentDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "contentDigest must be a sha256-prefixed lowercase SHA-256 digest"); + } + String expectedObjectKey = + "artifacts/sha256/" + contentDigest.substring(SHA256_PREFIX.length()); + if (!Objects.equals(expectedObjectKey, immutableObjectKey)) { + throw new IllegalArgumentException("immutableObjectKey must address contentDigest"); + } + } + + public static int compareUsageKeysUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = Byte.compareUnsigned(leftBytes[index], rightBytes[index]); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must be nonblank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " must not contain control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(fieldName + " must be valid UTF-8 text", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java index 4265e6884c..2b09e9d3e1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java @@ -6,6 +6,17 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; public interface PublishedReleaseBundleService { + /** + * Requires evidence already obtained over the authenticated World client before this transaction. + */ + PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + java.util.List participantDigests, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldEvidence); + PublishedReleaseBundleDto createFullVersionBundle( VersionDto version, String publishWorkflowId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java index 53f1c7aadb..bcd9c1ddc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java @@ -10,6 +10,16 @@ public interface VersionAssetArtifactService { Optional findState(String tenantId, long versionId); + VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId); + + /** + * Returns the recorded export candidate, or {@code null} when an exact initial STAGED intent has + * not recorded candidate evidence yet. Missing artifacts and malformed or partial evidence are + * errors. + */ + ExportedAssetManifest getExportCandidate(String tenantId, long versionId); + VersionAssetArtifactStateDto markExportedUnattested( String tenantId, long versionId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java new file mode 100644 index 0000000000..225c69b46a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.gamedesign.service; + +/** Owner-local immutable candidate evidence committed before any external byte write. */ +public interface VersionAssetExportCandidateService { + ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate); + + ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java new file mode 100644 index 0000000000..94c555ffa5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamedesign.service; + +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; + +/** Owner-local authoring and durable-readback operations for ordinary Version assets. */ +public interface VersionAssetPublicationService { + /** + * Adds an exact source row to a caller-tenant Draft Version mapping. The tenant string and + * numeric Version/asset ids are private owner keys, not external UUID identity aliases. + */ + void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType); + + /** Freezes the Draft mapping set once, or returns an earlier frozen selection after readback. */ + ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber); + + /** Independently reads and verifies an already committed durable selection. */ + ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index 2ccccc8651..24f62bbc0c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -1,18 +1,112 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; + static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; static final String REPAIR_ATTESTATION_MISMATCH = "REPAIR_ATTESTATION_MISMATCH"; static final String REPAIR_ATTESTED_ASSET_KEY_MISMATCH = "REPAIR_ATTESTED_ASSET_KEY_MISMATCH"; private PublishedReleaseBundleContract() {} + static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { + new ExportedAssetManifest( + bundle.manifestHash(), + Objects.requireNonNull(bundle.manifestSchemaVersion(), "manifestSchemaVersion"), + bundle.requiredManifestAssetKeys(), + Objects.requireNonNull(bundle.artifactDigests(), "artifactDigests")); + var evidence = + Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence"); + var request = evidence.request(); + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion()) + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null + || !request.canonicalTenantId().equals(bundle.canonicalTenantId()) + || !request.canonicalVersionId().equals(bundle.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.publishWorkflowId()) + || bundle.manifestSchemaVersion() == null + || bundle.artifactDigests() == null) { + throw new IllegalArgumentException( + "World selector differs from complete immutable release binding"); + } + var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + var seen = new HashSet(); + for (var participant : bundle.participantDigests()) { + if (!required.contains(participant.participantKey()) + || !seen.add(participant.participantKey()) + || !participant.succeeded() + || participant.baseVersionId() != null + || !Long.toString(bundle.versionId()).equals(participant.scopeValue()) + || !request.appliedCommitId().equals(participant.appliedCommitId()) + || participant.contentDigest() == null + || !participant.contentDigest().matches("[0-9a-f]{64}") + || !Objects.equals( + participant.digestSchemaVersion(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey()))) { + throw new IllegalArgumentException( + "World selector requires all exact successful release participants"); + } + if ("WORLD_MANAGEMENT".equals(participant.participantKey()) + && (!request.contentDigest().equals(participant.contentDigest()) + || request.digestSchemaVersion() != participant.digestSchemaVersion())) { + throw new IllegalArgumentException( + "World selector differs from World participant digest/schema"); + } + if ("GAME_LOGIC".equals(participant.participantKey()) + && (participant.abilitySchemaDigest() == null + || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}"))) { + throw new IllegalArgumentException( + "World selector release lacks Game Logic ability schema proof"); + } + } + if (seen.size() != required.size()) { + throw new IllegalArgumentException("World selector release lacks required participants"); + } + } + + static void requireExactSelectorRetry( + PublishedReleaseBundleDto stored, + VersionDto version, + String workflow, + ExportedAssetManifest manifest, + String generationRevision, + List participants, + WorldPublishedStartLocationEvidence evidence) { + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); + } + requireSelectorBinding(stored); + if (stored.versionNumber() != version.versionNumber() + || version.scriptOnly() + || version.scriptPatchVersion() != null + || !Objects.equals(stored.publishWorkflowId(), workflow) + || !Objects.equals(stored.manifestHash(), manifest.manifestHash()) + || !Objects.equals(stored.manifestSchemaVersion(), manifest.manifestSchemaVersion()) + || !Objects.equals(stored.artifactDigests(), manifest.artifactDigests()) + || !stored.requiredManifestAssetKeys().equals(manifest.requiredManifestAssetKeys()) + || !Objects.equals(stored.generationConfigRevision(), generationRevision) + || !stored.participantDigests().equals(participants) + || !Arrays.equals( + stored.worldPublishedStartLocationEvidence().canonicalBytes(), + evidence.canonicalBytes())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input"); + } + } + static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -22,6 +116,17 @@ static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { } } + /** + * Publication reconciliation only; does not widen launch or repair authorization/schema support. + */ + static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForRead(bundle); + } + static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalArgumentException( @@ -31,9 +136,26 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + /** + * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. + */ + static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForLaunch(bundle); + } + static void requireExactRepairMatch( PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) { requireSupportedSchemaForRead(bundle); + if (!Objects.equals(bundle.manifestSchemaVersion(), exportedManifest.manifestSchemaVersion()) + || !Objects.equals(bundle.artifactDigests(), exportedManifest.artifactDigests())) { + throw new IllegalStateException( + REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested artifact/schema proof"); + } if (!Objects.equals(bundle.manifestHash(), exportedManifest.manifestHash())) { throw new IllegalStateException( REPAIR_ATTESTATION_MISMATCH + ": repair could not reproduce the attested manifest hash"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 7b0ead7af9..4ec515bce7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -24,9 +24,11 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import tools.jackson.databind.ObjectMapper; @@ -79,6 +81,64 @@ public Optional findState(String tenantId, long ve return repository.findByTenantIdAndVersionId(tenantId, versionId).map(this::toDto); } + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId) { + if (tenantId == null + || tenantId.isBlank() + || versionId <= 0 + || versionNumber <= 0 + || workflowId == null + || workflowId.isBlank() + || workflowId.length() > 1024) { + throw new IllegalArgumentException("Exact asset export scope and workflow are required"); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (version.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.getVersionNumber() != versionNumber + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.getCanonicalTenantId() == null + || version.getCanonicalTenantId().equals(new UUID(0L, 0L)) + || version.getCanonicalVersionId() == null + || version.getCanonicalVersionId().equals(new UUID(0L, 0L)) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || version.getIdentitySourceProvenanceKind() == null + || !List.of("NEW_GAME_ROW", "RETAINED_GAME_V29") + .contains(version.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("ASSET_EXPORT_VERSION_CONFLICT"); + } + Optional stored = + repository.findByTenantIdAndVersionIdForUpdate(tenantId, versionId); + if (stored.isPresent()) { + VersionAssetArtifact artifact = stored.orElseThrow(); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getStateEpoch() <= 0 + || (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + && artifact.getArtifactState() != VersionAssetArtifactState.EXPORTED_UNATTESTED)) { + throw new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT"); + } + return toDto(artifact); + } + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId(tenantId); + artifact.setVersionId(versionId); + artifact.setExportedVersionNumber(versionNumber); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(workflowId); + return toDto(repository.save(artifact)); + } + @Override @Transactional public VersionAssetArtifactStateDto markExportedUnattested( @@ -87,10 +147,24 @@ public VersionAssetArtifactStateDto markExportedUnattested( int exportedVersionNumber, String workflowId, ExportedAssetManifest exportedManifest) { - VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); + VersionAssetArtifact artifact = + repository + .findByTenantIdAndVersionIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT")); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != exportedVersionNumber + || !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + if (artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED) { + return toDto(artifact); + } + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } artifact.setArtifactState(VersionAssetArtifactState.EXPORTED_UNATTESTED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exportedManifest.manifestHash()); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); @@ -101,6 +175,23 @@ public VersionAssetArtifactStateDto markExportedUnattested( return toDto(repository.save(artifact)); } + @Override + @Transactional(readOnly = true) + public ExportedAssetManifest getExportCandidate(String tenantId, long versionId) { + if (tenantId == null || tenantId.isBlank() || versionId <= 0) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + VersionAssetArtifact artifact = requireArtifact(tenantId, versionId); + if (!Objects.equals(tenantId, artifact.getTenantId()) + || !Objects.equals(versionId, artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + if (isInitialStagedIntentWithoutCandidate(artifact)) { + return null; + } + return candidateOf(artifact); + } + @Override @Transactional public VersionAssetArtifactStateDto markPublished( @@ -118,7 +209,7 @@ public VersionAssetArtifactStateDto markPublished( throw new IllegalStateException("REPAIR_ATTESTATION_MISMATCH"); } artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -139,8 +230,14 @@ public void markFailed( VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); artifact.setArtifactState(VersionAssetArtifactState.FAILED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); - artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + if (artifact.getManifestSchemaVersion() != null) { + if (exportedManifest != null && !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } else { + artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + } artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(errorCode); artifact.setLastErrorMessage(errorMessage); @@ -163,7 +260,7 @@ public VersionAssetArtifactStateDto tombstoneVersionAssets( throw new IllegalStateException("VERSION_ASSET_NOT_DELETABLE"); } artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(tombstoneWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -268,7 +365,7 @@ public VersionAssetPurgeWorkflowStatusDto beginPurgeVersionAssets( } String purgeWorkflowId = UUID.randomUUID().toString(); artifact.setArtifactState(VersionAssetArtifactState.PURGE_IN_PROGRESS); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(purgeWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -303,7 +400,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( artifact.getExportedVersionNumber(), deserializeKeys(artifact.getExportedManifestAssetKeysJson())); artifact.setArtifactState(VersionAssetArtifactState.PURGED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); artifact.setUpdatedAt(LocalDateTime.now()); @@ -318,7 +415,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( return toWorkflowDto(workflow); } catch (RuntimeException ex) { artifact.setArtifactState(VersionAssetArtifactState.PURGE_FAILED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode("PURGE_FINALIZATION_CONFLICT"); artifact.setLastErrorMessage(ex.getMessage()); artifact.setUpdatedAt(LocalDateTime.now()); @@ -363,11 +460,12 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(ex.getMessage().split(":", 2)[0]); artifact.setLastErrorMessage(ex.getMessage().split(":", 2)[1].trim()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setUpdatedAt(LocalDateTime.now()); repository.save(artifact); throw new IllegalStateException(artifact.getLastErrorCode()); } - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exported.manifestHash()); artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(null); @@ -447,6 +545,53 @@ private String serializeKeys(List keys) { } } + private ExportedAssetManifest candidateOf(VersionAssetArtifact artifact) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + try { + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + return new ExportedAssetManifest( + artifact.getManifestHash(), + artifact.getManifestSchemaVersion(), + deserializeKeys(artifact.getExportedManifestAssetKeysJson()), + digests); + } catch (Exception ex) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE", ex); + } + } + + private boolean isInitialStagedIntentWithoutCandidate(VersionAssetArtifact artifact) { + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getManifestHash() != null + || artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null) { + return false; + } + String keysJson = artifact.getExportedManifestAssetKeysJson(); + if (keysJson == null || keysJson.isBlank()) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + List keys = deserializeKeys(keysJson); + if (keys == null) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + return keys.isEmpty(); + } + private List deserializeKeys(String keysJson) { try { if (keysJson == null || keysJson.isBlank()) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java new file mode 100644 index 0000000000..9b5b1348b9 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** Commits exact candidate evidence before the exporter is allowed to write any object bytes. */ +@Service +public final class VersionAssetExportCandidateServiceImpl + implements VersionAssetExportCandidateService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CANDIDATE_CONFLICT = "ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final String CANDIDATE_NOT_FOUND = "ASSET_EXPORT_CANDIDATE_NOT_FOUND"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final String MANIFEST_USAGE_KEY = "manifest.json"; + private static final String BINARY_ARTIFACT_KIND = "BINARY"; + private final VersionRepository versionRepository; + private final GameRepository gameRepository; + private final PublishAttemptRepository attemptRepository; + private final VersionAssetArtifactRepository artifactRepository; + private final VersionAssetPublicationService publicationService; + private final ObjectMapper objectMapper; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetExportCandidateServiceImpl( + VersionRepository versionRepository, + GameRepository gameRepository, + PublishAttemptRepository attemptRepository, + VersionAssetArtifactRepository artifactRepository, + VersionAssetPublicationService publicationService, + PlatformTransactionManager transactionManager, + ObjectMapper objectMapper) { + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository"); + this.attemptRepository = Objects.requireNonNull(attemptRepository, "attemptRepository"); + this.artifactRepository = Objects.requireNonNull(artifactRepository, "artifactRepository"); + this.publicationService = Objects.requireNonNull(publicationService, "publicationService"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + + ownerWrite = new TransactionTemplate(requiredTransactionManager); + ownerWrite.setName("version-asset-export-candidate-write"); + ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerWrite.setTimeout(15); + + ownerRead = new TransactionTemplate(requiredTransactionManager); + ownerRead.setName("version-asset-export-candidate-readback"); + ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerRead.setReadOnly(true); + ownerRead.setTimeout(15); + } + + @Override + public ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + requireScope(tenantId, versionNumber); + Objects.requireNonNull(candidate, "candidate"); + ExportedAssetManifest committed = + ownerWrite.execute(status -> recordInOwnerTransaction(tenantId, versionNumber, candidate)); + if (committed == null) { + throw new IllegalStateException("Export candidate transaction returned no proof"); + } + // TransactionTemplate returns only after commit. The caller performs its own independent + // readback before it is permitted to write any object-store bytes. + return committed; + } + + @Override + public ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber) { + requireScope(tenantId, versionNumber); + ExportedAssetManifest result = + ownerRead.execute(status -> readInOwnerTransaction(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException("Independent export candidate readback returned no proof"); + } + return result; + } + + private ExportedAssetManifest recordInOwnerTransaction( + String tenantId, int versionNumber, ExportedAssetManifest requested) { + if (gameRepository.findByTenantIdForUpdate(tenantId) == null) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + Version initiallyFound = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + var initialArtifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + var attempt = + attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); + // Standalone private candidate recording is not publication authority. If an actual selected + // attempt exists, its immutable operation must still be open before any new candidate + // admission. + if (attempt.isPresent()) { + var current = attempt.get(); + if (!Objects.equals(current.getTenantId(), tenantId) + || !Objects.equals(current.getVersionId(), initiallyFound.getId()) + || current.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + if (current.getRequestDigest() != null) attemptRepository.requirePublicationPending(current); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionIdForUpdate(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + CandidateEvidence requestedEvidence = candidateEvidence(requested, snapshot); + if (hasAnyCandidateEvidence(artifact)) { + CandidateEvidence storedEvidence = storedEvidence(artifact, version, snapshot); + if (!sameCandidate(requested, storedEvidence.manifest()) + || !sameEvidence(requestedEvidence, storedEvidence)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return storedEvidence.manifest(); + } + + if (version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() != snapshot.capturedVersionStateEpoch() + || artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getManifestHash() != null + || !isEmptyKeysJson(artifact.getExportedManifestAssetKeysJson())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + long nextEpoch; + try { + nextEpoch = Math.addExact(artifact.getStateEpoch(), 1L); + } catch (ArithmeticException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + artifact.setManifestHash(requested.manifestHash()); + artifact.setManifestSchemaVersion(requested.manifestSchemaVersion()); + artifact.setArtifactDigestsJson(serialize(requested.artifactDigests())); + artifact.setPublishedObjectProofsJson(serialize(requestedEvidence.objectProofs())); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + artifact.setExportedManifestAssetKeysJson(serialize(requested.requiredManifestAssetKeys())); + artifact.setStateEpoch(nextEpoch); + + VersionAssetArtifact saved = artifactRepository.save(artifact); + CandidateEvidence readback = storedEvidence(saved, version, snapshot); + if (!sameEvidence(requestedEvidence, readback) + || !sameCandidate(requested, readback.manifest())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return readback.manifest(); + } + + private ExportedAssetManifest readInOwnerTransaction(String tenantId, int versionNumber) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + if (!hasAnyCandidateEvidence(artifact)) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + return storedEvidence(artifact, version, snapshot).manifest(); + } + + private ExportSnapshot readAndValidateSnapshot( + String tenantId, int versionNumber, Version version) { + ExportSnapshot snapshot = publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (snapshot == null + || !Objects.equals(snapshot.tenantId(), tenantId) + || snapshot.versionId() != version.getId() + || snapshot.versionNumber() != versionNumber + || snapshot.capturedVersionStateEpoch() <= 0 + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() < snapshot.capturedVersionStateEpoch() + || !Objects.equals(snapshot.canonicalTenantId(), version.getCanonicalTenantId()) + || !Objects.equals(snapshot.canonicalVersionId(), version.getCanonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return snapshot; + } + + private CandidateEvidence storedEvidence( + VersionAssetArtifact artifact, Version version, ExportSnapshot snapshot) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getManifestSchemaVersion() != 1 + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || artifact.getCandidateSnapshotVersionId() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), version.getId()) + || artifact.getManifestHash() == null + || artifact.getExportedVersionNumber() != snapshot.versionNumber() + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + try { + List keys = + objectMapper.readValue( + requireJson(artifact.getExportedManifestAssetKeysJson()), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + List proofs = + objectMapper.readValue( + artifact.getPublishedObjectProofsJson(), + objectMapper.getTypeFactory().constructCollectionType(List.class, ObjectProof.class)); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + artifact.getManifestHash(), artifact.getManifestSchemaVersion(), keys, digests); + CandidateEvidence verified = candidateEvidence(manifest, snapshot); + if (!Objects.equals(artifact.getArtifactDigestsJson(), serialize(digests)) + || !Objects.equals(artifact.getPublishedObjectProofsJson(), serialize(proofs)) + || !Objects.equals(artifact.getExportedManifestAssetKeysJson(), serialize(keys)) + || !Objects.equals(proofs, verified.objectProofs())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return verified; + } catch (RuntimeException exception) { + if (CANDIDATE_CONFLICT.equals(exception.getMessage())) { + throw exception; + } + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private CandidateEvidence candidateEvidence( + ExportedAssetManifest manifest, ExportSnapshot snapshot) { + if (manifest.manifestSchemaVersion() != 1 + || manifest.manifestHash() == null + || !manifest.manifestHash().matches("sha256:[0-9a-f]{64}") + || !Objects.equals( + manifest.requiredManifestAssetKeys(), + snapshot.items().stream().map(AssetSelection::usageKey).toList()) + || manifest.artifactDigests().size() != snapshot.items().size()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + LinkedHashMap proofsByKey = new LinkedHashMap<>(); + for (int index = 0; index < snapshot.items().size(); index++) { + AssetSelection source = snapshot.items().get(index); + PublishedArtifactDigest digest = manifest.artifactDigests().get(index); + if (source == null + || digest == null + || source.usageKey() == null + || source.usageKey().isBlank() + || !isCanonicalText(source.usageKey()) + || MANIFEST_USAGE_KEY.equals(source.usageKey()) + || source.assetId() <= 0 + || source.bytes() == null + || source.contentType() == null + || source.contentType().isBlank() + || !source.contentType().equals(source.contentType().trim()) + || source.contentType().contains("\r") + || source.contentType().contains("\n") + || !isCanonicalText(source.contentType()) + || source.contentDigest() == null + || !source.contentDigest().matches("sha256:[0-9a-f]{64}") + || !source.contentDigest().equals(digest(source.bytes())) + || !usageKeys.add(source.usageKey()) + || !assetIds.add(source.assetId()) + || !Objects.equals(digest.usageKey(), source.usageKey()) + || !Objects.equals(digest.artifactKind(), BINARY_ARTIFACT_KIND) + || digest.artifactSchemaVersion() != 1 + || !Objects.equals(digest.contentType(), source.contentType()) + || !Objects.equals(digest.contentDigest(), source.contentDigest()) + || !Objects.equals( + digest.immutableObjectKey(), + ARTIFACT_OBJECT_ROOT + source.contentDigest().substring(7))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + putProof(proofsByKey, digest.immutableObjectKey(), digest.contentDigest()); + } + + String manifestDigest = manifest.manifestHash(); + putProof( + proofsByKey, + MANIFEST_OBJECT_ROOT + manifestDigest.substring("sha256:".length()), + manifestDigest); + List objectProofs = + proofsByKey.values().stream() + .sorted(Comparator.comparing(ObjectProof::immutableObjectKey)) + .toList(); + return new CandidateEvidence(manifest, objectProofs); + } + + private void putProof( + LinkedHashMap proofsByKey, String objectKey, String contentDigest) { + ObjectProof proof = new ObjectProof(objectKey, contentDigest); + ObjectProof existing = proofsByKey.putIfAbsent(objectKey, proof); + if (existing != null && !existing.equals(proof)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateVersion(Version version, String tenantId, int versionNumber) { + if (version.getId() == null + || version.getId() <= 0 + || !Objects.equals(version.getTenantId(), tenantId) + || version.getVersionNumber() != versionNumber + || version.getVersionState() == null + || !(version.getVersionState() == VersionLifecycleState.DRAFT + || version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || !isCanonicalUuid(version.getCanonicalTenantId()) + || !isCanonicalUuid(version.getCanonicalVersionId()) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || !("NEW_GAME_ROW".equals(version.getIdentitySourceProvenanceKind()) + || "RETAINED_GAME_V29".equals(version.getIdentitySourceProvenanceKind()))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateArtifactScope( + VersionAssetArtifact artifact, String tenantId, Version version) { + if (artifact.getId() == null + || artifact.getId() <= 0 + || !Objects.equals(artifact.getTenantId(), tenantId) + || !Objects.equals(artifact.getVersionId(), version.getId()) + || artifact.getArtifactState() == null + || !(artifact.getArtifactState() == VersionAssetArtifactState.STAGED + || artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED + || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED) + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private boolean hasAnyCandidateEvidence(VersionAssetArtifact artifact) { + return artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null; + } + + private boolean isEmptyKeysJson(String json) { + try { + List keys = + objectMapper.readValue( + requireJson(json), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + return keys.isEmpty() && Objects.equals(json, serialize(keys)); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static boolean sameCandidate(ExportedAssetManifest left, ExportedAssetManifest right) { + return Objects.equals(left, right); + } + + private static boolean sameEvidence(CandidateEvidence left, CandidateEvidence right) { + return sameCandidate(left.manifest(), right.manifest()) + && Objects.equals(left.objectProofs(), right.objectProofs()); + } + + private String serialize(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static String requireJson(String json) { + if (json == null || json.isBlank()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return json; + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean isCanonicalText(String value) { + if (value == null || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException exception) { + return false; + } + } + + private static void requireScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("Exact tenant and Version number are required"); + } + } + + /** Exact immutable key/content-digest proof; candidate rows use camel-case record JSON fields. */ + private record ObjectProof(String immutableObjectKey, String contentDigest) {} + + private record CandidateEvidence(ExportedAssetManifest manifest, List objectProofs) { + private CandidateEvidence { + objectProofs = List.copyOf(objectProofs); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java new file mode 100644 index 0000000000..cd7a2a21fe --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Commits durable Version asset selections independently before exposing verified readback. */ +@Service +public final class VersionAssetPublicationServiceImpl implements VersionAssetPublicationService { + private final VersionAssetPublicationRepository repository; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetPublicationServiceImpl( + PlatformTransactionManager transactionManager, VersionAssetPublicationRepository repository) { + this.repository = Objects.requireNonNull(repository, "repository"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + this.ownerWrite = new TransactionTemplate(requiredTransactionManager); + this.ownerWrite.setName("version-asset-publication-write"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setTimeout(15); + + this.ownerRead = new TransactionTemplate(requiredTransactionManager); + this.ownerRead.setName("version-asset-publication-readback"); + this.ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerRead.setReadOnly(true); + this.ownerRead.setTimeout(15); + } + + @Override + public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireTenantId(tenantId); + if (versionId <= 0 || assetId <= 0) { + throw new IllegalArgumentException("Version and asset owner keys must be positive"); + } + ownerWrite.executeWithoutResult( + status -> repository.associateDraftAsset(tenantId, versionId, assetId, usageType)); + } + + @Override + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot committed = + ownerWrite.execute(status -> repository.freezeOrReadSnapshot(tenantId, versionNumber)); + if (committed == null) { + throw new IllegalStateException("Version asset snapshot transaction returned no proof"); + } + + ExportSnapshot readback = readFrozenSnapshot(tenantId, versionNumber); + if (!sameSnapshot(committed, readback)) { + throw new IllegalStateException( + "Committed Version asset snapshot did not match independent readback"); + } + return readback; + } + + @Override + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot result = + ownerRead.execute(status -> repository.readFrozenSnapshot(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException( + "Independent Version asset snapshot readback returned no proof"); + } + return result; + } + + private static boolean sameSnapshot(ExportSnapshot left, ExportSnapshot right) { + if (!Objects.equals(left.tenantId(), right.tenantId()) + || left.versionId() != right.versionId() + || left.versionNumber() != right.versionNumber() + || left.capturedVersionStateEpoch() != right.capturedVersionStateEpoch() + || !Objects.equals(left.canonicalTenantId(), right.canonicalTenantId()) + || !Objects.equals(left.canonicalVersionId(), right.canonicalVersionId())) { + return false; + } + List leftItems = left.items(); + List rightItems = right.items(); + if (leftItems.size() != rightItems.size()) { + return false; + } + for (int index = 0; index < leftItems.size(); index++) { + AssetSelection leftItem = leftItems.get(index); + AssetSelection rightItem = rightItems.get(index); + if (!Objects.equals(leftItem.usageKey(), rightItem.usageKey()) + || leftItem.assetId() != rightItem.assetId() + || !Objects.equals(leftItem.contentType(), rightItem.contentType()) + || !Objects.equals(leftItem.contentDigest(), rightItem.contentDigest()) + || !Arrays.equals(leftItem.bytes(), rightItem.bytes())) { + return false; + } + } + return true; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } +} diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 4c8251d4e5..170ec88282 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -51,6 +51,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index cfa32714ea..3ee2e497fc 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -62,6 +62,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies http: enabled: true role-requirement: PRIVILEGED @@ -79,3 +81,6 @@ firemud: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + game-design: + published-realm-entry-policy-read: + enabled: ${FIREMUD_PUBLISHED_REALM_ENTRY_POLICY_READ_ENABLED:false} diff --git a/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql new file mode 100644 index 0000000000..c96657e892 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql @@ -0,0 +1,116 @@ +ALTER TABLE version + ADD COLUMN canonical_version_id UUID, + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN identity_source_game_row_id BIGINT, + ADD COLUMN identity_source_game_tenant_key VARCHAR(36), + ADD COLUMN identity_source_provenance_kind VARCHAR(32); + +ALTER TABLE version + ADD CONSTRAINT uq_version_canonical_version_id UNIQUE (canonical_version_id), + ADD CONSTRAINT fk_version_identity_source_game + FOREIGN KEY (identity_source_game_row_id) REFERENCES game(id), + ADD CONSTRAINT chk_version_canonical_identity_shape CHECK ( + (canonical_version_id IS NULL + AND canonical_tenant_id IS NULL + AND identity_source_game_row_id IS NULL + AND identity_source_game_tenant_key IS NULL + AND identity_source_provenance_kind IS NULL) + OR + (canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND identity_source_game_row_id IS NOT NULL + AND identity_source_game_row_id > 0 + AND identity_source_game_tenant_key IS NOT NULL + AND char_length(identity_source_game_tenant_key) BETWEEN 1 AND 36 + AND identity_source_game_tenant_key !~ '^[[:space:]]*$' + AND identity_source_provenance_kind IS NOT NULL + AND identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) + ); + +-- [jooq ignore start] +CREATE FUNCTION enforce_version_canonical_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_version_id IS NOT NULL THEN + RAISE EXCEPTION 'canonical Version identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id IS NULL + OR NEW.identity_source_game_row_id IS NULL + OR NEW.identity_source_game_tenant_key IS NULL + OR NEW.identity_source_provenance_kind IS NULL THEN + RAISE EXCEPTION 'new Version rows require an owner-issued canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.identity_source_game_row_id + AND g.tenant_id = NEW.identity_source_game_tenant_key + AND NEW.tenant_id = g.tenant_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'canonical Version identity source does not match its exact game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.canonical_version_id IS NULL THEN + IF NEW.canonical_version_id IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.identity_source_game_row_id IS NOT NULL + OR NEW.identity_source_game_tenant_key IS NOT NULL + OR NEW.identity_source_provenance_kind IS NOT NULL THEN + RAISE EXCEPTION 'retained Version rows cannot be assigned a canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.identity_source_game_row_id IS DISTINCT FROM OLD.identity_source_game_row_id + OR NEW.identity_source_game_tenant_key IS DISTINCT FROM OLD.identity_source_game_tenant_key + OR NEW.identity_source_provenance_kind IS DISTINCT FROM OLD.identity_source_provenance_kind THEN + RAISE EXCEPTION 'canonical Version identity and its tenant source are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_immutable + BEFORE INSERT OR UPDATE OR DELETE ON version + FOR EACH ROW + EXECUTE FUNCTION enforce_version_canonical_identity(); + +CREATE FUNCTION reject_version_canonical_identity_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version WHERE canonical_version_id IS NOT NULL) THEN + RAISE EXCEPTION 'canonical Version identities cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_no_truncate + BEFORE TRUNCATE ON version + FOR EACH STATEMENT + EXECUTE FUNCTION reject_version_canonical_identity_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql new file mode 100644 index 0000000000..298842ed3f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql @@ -0,0 +1,86 @@ +ALTER TABLE version + ADD CONSTRAINT uq_version_release_canonical_identity + UNIQUE (id, canonical_tenant_id, canonical_version_id); + +ALTER TABLE published_release_bundle + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_version_id UUID, + ADD CONSTRAINT chk_published_release_bundle_canonical_identity CHECK ( + (canonical_tenant_id IS NULL AND canonical_version_id IS NULL) + OR + (canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ), + ADD CONSTRAINT fk_published_release_bundle_canonical_version + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id); + +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_immutability() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published release bundle metadata is retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_tenant_id IS NULL + OR NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'new published release bundles require a non-nil canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + WHERE v.id = NEW.version_id + AND v.tenant_id = NEW.tenant_id + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id > 0 + AND v.identity_source_game_tenant_key = v.tenant_id + AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'published release bundle identity does not match its exact Version and Game source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'published release bundle attestation is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_immutable + BEFORE INSERT OR UPDATE OR DELETE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_immutability(); + +CREATE FUNCTION reject_published_release_bundle_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM published_release_bundle) THEN + RAISE EXCEPTION 'published release bundle metadata cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_no_truncate + BEFORE TRUNCATE ON published_release_bundle + FOR EACH STATEMENT + EXECUTE FUNCTION reject_published_release_bundle_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql new file mode 100644 index 0000000000..d539f6021d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql @@ -0,0 +1,147 @@ +ALTER TABLE launch_descriptor ADD COLUMN descriptor_schema_version SMALLINT; +ALTER TABLE launch_descriptor ADD COLUMN target_namespace VARCHAR(63); +ALTER TABLE launch_descriptor ADD COLUMN canonical_tenant_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN world_slug VARCHAR(120); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_operation_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN original_request_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN source_evidence_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN outcome_status VARCHAR(16) NOT NULL DEFAULT 'SUCCESS'; +ALTER TABLE launch_descriptor ADD COLUMN failure_code VARCHAR(64); +ALTER TABLE launch_descriptor ADD COLUMN failure_message TEXT; + +-- A deterministic denial is a request outcome, not a descriptor. Keep the successful tuple +-- nullable at the row level and require its complete shape below for SUCCESS outcomes. +ALTER TABLE launch_descriptor ALTER COLUMN launch_descriptor_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN game_template_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN runtime_flags_json DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN generation_config_revision DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_state_epoch DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN release_bundle_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN published_release_bundle_ref DROP NOT NULL; + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_authored_binding_complete + CHECK ( + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NULL + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND world_slug IS NULL + AND authored_world_source_operation_id IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL + AND original_request_json IS NULL + AND source_evidence_json IS NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND request_hash IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL) + OR + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NOT NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL + AND request_hash = request_digest) + OR + (outcome_status = 'FAILED' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NOT NULL + AND failure_code IN ( + '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', + 'SCHEMA_VERSION_UNSUPPORTED') + AND failure_message IS NOT NULL + AND CHAR_LENGTH(failure_message) > 0 + AND launch_descriptor_id IS NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NULL + AND control_plane_request_id IS NOT NULL + AND request_hash = request_digest + AND version_id IS NULL + AND script_patch_version IS NULL + AND runtime_flags_json IS NULL + AND generation_config_revision IS NULL + AND version_state_epoch IS NULL + AND release_bundle_id IS NULL + AND published_release_bundle_ref IS NULL + AND remap_set_id IS NULL) + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_outcome_status + CHECK (outcome_status IN ('SUCCESS', 'FAILED')); + +CREATE UNIQUE INDEX uq_launch_descriptor_bound_request + ON launch_descriptor(target_namespace, canonical_tenant_id, control_plane_request_id) + WHERE descriptor_schema_version IS NOT NULL; + +-- PostgreSQL enforces the immutable history; the schema generator needs only the table shape. +-- [jooq ignore start] +CREATE FUNCTION reject_launch_descriptor_history_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_immutable + BEFORE UPDATE OR DELETE ON launch_descriptor + FOR EACH ROW + EXECUTE FUNCTION reject_launch_descriptor_history_mutation(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql new file mode 100644 index 0000000000..d1a0bc0b5b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql @@ -0,0 +1,56 @@ +ALTER TABLE published_release_bundle + ADD COLUMN published_release_bundle_ref VARCHAR(128); + +ALTER TABLE published_release_bundle + ADD CONSTRAINT ck_published_release_bundle_ref_nonblank + CHECK (published_release_bundle_ref IS NULL OR BTRIM(published_release_bundle_ref) <> ''); + +CREATE UNIQUE INDEX uq_published_release_bundle_opaque_ref + ON published_release_bundle(published_release_bundle_ref) + WHERE published_release_bundle_ref IS NOT NULL; + +-- Retained bundles intentionally remain NULL. New owner inserts must supply an identity, and +-- once assigned the opaque reference cannot be changed independently of the bundle. +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_reference() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.published_release_bundle_ref IS NULL + OR BTRIM(NEW.published_release_bundle_ref) = '' THEN + RAISE EXCEPTION 'new published release bundles require an opaque reference'; + END IF; + ELSE + IF NEW.published_release_bundle_ref IS DISTINCT FROM OLD.published_release_bundle_ref THEN + RAISE EXCEPTION 'published release bundle reference is immutable'; + END IF; + IF OLD.published_release_bundle_ref IS NOT NULL AND ( + NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.version_number IS DISTINCT FROM OLD.version_number + OR NEW.attestation_schema_version IS DISTINCT FROM OLD.attestation_schema_version + OR NEW.publish_workflow_id IS DISTINCT FROM OLD.publish_workflow_id + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.generation_config_revision IS DISTINCT FROM OLD.generation_config_revision + OR NEW.required_manifest_asset_keys_json + IS DISTINCT FROM OLD.required_manifest_asset_keys_json + OR NEW.participant_digests_json IS DISTINCT FROM OLD.participant_digests_json + OR NEW.command_definitions_json IS DISTINCT FROM OLD.command_definitions_json + OR NEW.script_only IS DISTINCT FROM OLD.script_only + OR NEW.script_patch_version IS DISTINCT FROM OLD.script_patch_version + OR NEW.published_at IS DISTINCT FROM OLD.published_at) THEN + RAISE EXCEPTION 'published release bundle attestation is immutable'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_published_release_bundle_reference + BEFORE INSERT OR UPDATE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_reference(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql new file mode 100644 index 0000000000..36656d1c58 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql @@ -0,0 +1,348 @@ +ALTER TABLE game + ADD CONSTRAINT uq_game_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE version + ADD CONSTRAINT uq_version_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE game_assets + ADD CONSTRAINT uq_game_assets_tenant_id_id UNIQUE (tenant_id, id), + ADD CONSTRAINT uq_game_assets_tenant_id_name UNIQUE (tenant_id, id, file_name); + +CREATE TABLE version_asset ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + asset_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + usage_type VARCHAR(100), + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset PRIMARY KEY (tenant_id, version_id, asset_id), + CONSTRAINT uq_version_asset_usage UNIQUE (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_exact UNIQUE (tenant_id, version_id, asset_id, usage_key), + CONSTRAINT fk_version_asset_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset FOREIGN KEY (tenant_id, asset_id) + REFERENCES game_assets (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset_name FOREIGN KEY (tenant_id, asset_id, usage_key) + REFERENCES game_assets (tenant_id, id, file_name) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_usage_key CHECK (char_length(usage_key) > 0) +); + +CREATE TABLE version_asset_export_snapshot ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_number INTEGER NOT NULL, + captured_version_state_epoch BIGINT NOT NULL, + item_count INTEGER NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset_export_snapshot PRIMARY KEY (tenant_id, version_id), + CONSTRAINT fk_version_asset_snapshot_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_snapshot_values CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_number > 0 + AND captured_version_state_epoch > 0 + AND item_count >= 0 + ) +); + +CREATE TABLE version_asset_export_item ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + asset_id BIGINT NOT NULL, + content_type VARCHAR(100) NOT NULL, + content_hash VARCHAR(71) NOT NULL, + byte_size BIGINT NOT NULL, + CONSTRAINT pk_version_asset_export_item PRIMARY KEY (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_export_item_asset UNIQUE (tenant_id, version_id, asset_id), + CONSTRAINT fk_version_asset_export_item_snapshot FOREIGN KEY (tenant_id, version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id) + DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_version_asset_export_item_mapping FOREIGN KEY + (tenant_id, version_id, asset_id, usage_key) + REFERENCES version_asset (tenant_id, version_id, asset_id, usage_key) + ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_export_item_hash CHECK (content_hash ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_version_asset_export_item_size CHECK (byte_size >= 0) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_version_asset_mapping() RETURNS trigger AS $$ +DECLARE + target_tenant_id VARCHAR(36); + target_version_id BIGINT; + target_state VARCHAR(32); + target_epoch BIGINT; +BEGIN + IF TG_OP = 'UPDATE' AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.asset_id IS DISTINCT FROM OLD.asset_id + OR NEW.usage_key IS DISTINCT FROM OLD.usage_key + ) THEN + RAISE EXCEPTION 'version asset association identity is immutable; create a new Draft mapping' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + target_tenant_id := OLD.tenant_id; + target_version_id := OLD.version_id; + ELSE + target_tenant_id := NEW.tenant_id; + target_version_id := NEW.version_id; + END IF; + + SELECT v.version_state, v.version_state_epoch + INTO target_state, target_epoch + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = target_tenant_id AND v.id = target_version_id + AND v.canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND v.canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + FOR UPDATE OF v; + + IF NOT FOUND THEN + RAISE EXCEPTION 'version asset mapping requires the exact canonical tenant Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF target_state <> 'DRAFT' OR target_epoch IS NULL OR target_epoch <= 0 THEN + RAISE EXCEPTION 'version asset mappings can change only while the Version is DRAFT' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = target_tenant_id AND s.version_id = target_version_id + ) THEN + RAISE EXCEPTION 'version asset mappings are frozen by the durable export snapshot' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP <> 'DELETE' AND NOT EXISTS ( + SELECT 1 FROM game_assets a + WHERE a.tenant_id = NEW.tenant_id + AND a.id = NEW.asset_id + AND a.file_name = NEW.usage_key + ) THEN + RAISE EXCEPTION 'version asset usage key must equal the exact source file name' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_mapping_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_mapping(); + +CREATE FUNCTION guard_version_asset_export_item() RETURNS trigger AS $$ +DECLARE + source_type VARCHAR(100); + source_size BIGINT; + target_state VARCHAR(32); +BEGIN + IF TG_OP <> 'INSERT' THEN + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = OLD.tenant_id AND s.version_id = OLD.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END IF; + + SELECT version_state INTO target_state + FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + FOR UPDATE; + IF NOT FOUND OR target_state <> 'DRAFT' THEN + RAISE EXCEPTION 'version asset export items require the exact Draft Version row' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = NEW.tenant_id AND s.version_id = NEW.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT a.content_type, octet_length(a.data)::BIGINT + INTO source_type, source_size + FROM game_assets a + JOIN version_asset va + ON va.tenant_id = a.tenant_id + AND va.asset_id = a.id + AND va.tenant_id = NEW.tenant_id + AND va.version_id = NEW.version_id + AND va.usage_key = NEW.usage_key + AND va.asset_id = NEW.asset_id + WHERE a.tenant_id = NEW.tenant_id AND a.id = NEW.asset_id; + + IF NOT FOUND OR source_type IS DISTINCT FROM NEW.content_type + OR source_size IS DISTINCT FROM NEW.byte_size THEN + RAISE EXCEPTION 'version asset export item source metadata does not match game_assets' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_item_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_item + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_item(); + +CREATE FUNCTION guard_version_asset_export_snapshot() RETURNS trigger AS $$ +DECLARE + source_version_number INTEGER; + source_epoch BIGINT; + source_state VARCHAR(32); + source_canonical_tenant_id UUID; + source_canonical_version_id UUID; + item_rows BIGINT; + mapping_rows BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'version asset export snapshot headers are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_number, + v.version_state_epoch, + v.version_state, + v.canonical_tenant_id, + v.canonical_version_id + INTO source_version_number, + source_epoch, + source_state, + source_canonical_tenant_id, + source_canonical_version_id + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = NEW.tenant_id AND v.id = NEW.version_id + FOR UPDATE OF v; + + IF NOT FOUND + OR source_state <> 'DRAFT' + OR source_epoch IS NULL OR source_epoch <= 0 + OR source_version_number IS DISTINCT FROM NEW.version_number + OR source_epoch IS DISTINCT FROM NEW.captured_version_state_epoch + OR source_canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR source_canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR source_canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR source_canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'version asset export snapshot requires the exact canonical Draft Version source' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT count(*) INTO item_rows + FROM version_asset_export_item i + WHERE i.tenant_id = NEW.tenant_id AND i.version_id = NEW.version_id; + SELECT count(*) INTO mapping_rows + FROM version_asset va + WHERE va.tenant_id = NEW.tenant_id AND va.version_id = NEW.version_id; + IF item_rows <> NEW.item_count OR mapping_rows <> NEW.item_count THEN + RAISE EXCEPTION 'version asset export snapshot item count does not prove the complete mapping set' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_snapshot_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_snapshot + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_snapshot(); + +CREATE FUNCTION guard_frozen_game_asset_source() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM version_asset_export_item i + WHERE i.tenant_id = OLD.tenant_id AND i.asset_id = OLD.id + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.file_name IS DISTINCT FROM OLD.file_name + OR NEW.content_type IS DISTINCT FROM OLD.content_type + OR NEW.data IS DISTINCT FROM OLD.data THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source + BEFORE UPDATE OR DELETE ON game_assets + FOR EACH ROW + EXECUTE FUNCTION guard_frozen_game_asset_source(); + +CREATE FUNCTION reject_frozen_asset_publication_truncate() RETURNS trigger AS $$ +BEGIN + IF TG_TABLE_NAME = 'game_assets' AND EXISTS ( + SELECT 1 FROM version_asset_export_item + ) THEN + RAISE EXCEPTION 'game asset source rows are retained by frozen version snapshots' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME IN ('version_asset', 'version_asset_export_item', 'version_asset_export_snapshot') + AND EXISTS (SELECT 1 FROM version_asset_export_snapshot) THEN + RAISE EXCEPTION 'frozen version asset publication evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source_no_truncate + BEFORE TRUNCATE ON game_assets + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_mapping_no_truncate + BEFORE TRUNCATE ON version_asset + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_item_no_truncate + BEFORE TRUNCATE ON version_asset_export_item + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_snapshot_no_truncate + BEFORE TRUNCATE ON version_asset_export_snapshot + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql new file mode 100644 index 0000000000..ac4bf05d03 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql @@ -0,0 +1,75 @@ +ALTER TABLE published_release_bundle + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD CONSTRAINT chk_published_asset_digest_evidence_shape CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL) + ); + +-- Existing immutable release rows remain explicitly without complete asset proof. +-- V35.2's INSERT/UPDATE/DELETE guard also protects these added attestation fields. +-- Do not backfill retained evidence from mutable assets or object-store listings. + +ALTER TABLE version_asset_artifact + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD COLUMN published_object_proofs_json TEXT, + ADD COLUMN candidate_snapshot_version_id BIGINT, + ADD CONSTRAINT chk_asset_export_candidate_evidence CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL + AND published_object_proofs_json IS NULL AND candidate_snapshot_version_id IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL + AND published_object_proofs_json IS NOT NULL + AND candidate_snapshot_version_id IS NOT NULL AND manifest_hash IS NOT NULL + AND candidate_snapshot_version_id = version_id + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_asset_export_candidate_snapshot + FOREIGN KEY (tenant_id, candidate_snapshot_version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id); + +-- [jooq ignore start] +CREATE FUNCTION guard_asset_export_candidate_evidence() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.manifest_schema_version IS NOT NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN OLD; + END IF; + IF OLD.manifest_schema_version IS NOT NULL AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.exported_version_number IS DISTINCT FROM OLD.exported_version_number + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.manifest_schema_version IS DISTINCT FROM OLD.manifest_schema_version + OR NEW.artifact_digests_json IS DISTINCT FROM OLD.artifact_digests_json + OR NEW.published_object_proofs_json IS DISTINCT FROM OLD.published_object_proofs_json + OR NEW.candidate_snapshot_version_id IS DISTINCT FROM OLD.candidate_snapshot_version_id + OR NEW.exported_manifest_asset_keys_json IS DISTINCT FROM OLD.exported_manifest_asset_keys_json + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_immutable + BEFORE UPDATE OR DELETE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_asset_export_candidate_evidence(); + +CREATE FUNCTION guard_asset_export_candidate_truncate() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version_asset_artifact WHERE manifest_schema_version IS NOT NULL) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_no_truncate + BEFORE TRUNCATE ON version_asset_artifact + FOR EACH STATEMENT EXECUTE FUNCTION guard_asset_export_candidate_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql new file mode 100644 index 0000000000..b002f13613 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql @@ -0,0 +1,11 @@ +ALTER TABLE published_release_bundle + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE launch_descriptor + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE version_asset_artifact + ALTER COLUMN last_error_message TYPE TEXT; + +ALTER TABLE publish_attempt + ALTER COLUMN failure_message TYPE TEXT; diff --git a/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql new file mode 100644 index 0000000000..1dfcbba765 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql @@ -0,0 +1,865 @@ +CREATE TABLE game_design_draft_commit ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + workflow_state VARCHAR(32) NOT NULL DEFAULT 'QUEUED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ), + CONSTRAINT uq_gd_draft_commit_target_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + commit_id + ), + CONSTRAINT uq_gd_draft_commit_exact_identity UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_canonical_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_draft_commit_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_draft_commit_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_binding_json CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_state CHECK ( + workflow_state IN ( + 'QUEUED', 'APPLYING', 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', + 'REJECTED', 'FAILED_NONPUBLICATION' + ) + ) +); + +CREATE TABLE game_design_draft_commit_owner_result ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL, + status VARCHAR(24) NOT NULL, + result_commit_id UUID, + result_binding_digest VARCHAR(71), + result_identity VARCHAR(512), + result_bytes BYTEA, + applied_units_json TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_owner_result PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + owner + ), + CONSTRAINT fk_gd_draft_commit_owner_result_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_owner CHECK ( + owner IN ( + 'WORLD_MANAGEMENT', + 'ENTITY_MANAGEMENT', + 'GAME_LOGIC', + 'AUTOMATION_SCRIPTING', + 'GAME_DESIGN_CONTROL_PLANE' + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_status CHECK ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS', 'APPLIED', 'REJECTED', 'UNKNOWN') + ), + CONSTRAINT chk_gd_draft_commit_owner_result_shape CHECK ( + ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS') + AND result_commit_id IS NULL + AND result_binding_digest IS NULL + AND result_identity IS NULL + AND result_bytes IS NULL + AND applied_units_json IS NULL + ) + OR + ( + status = 'UNKNOWN' + AND ( + (result_identity IS NULL AND result_bytes IS NULL) + OR (result_identity IS NOT NULL AND result_bytes IS NOT NULL) + ) + AND ( + (result_commit_id IS NULL AND result_binding_digest IS NULL AND applied_units_json IS NULL) + OR (result_commit_id IS NOT NULL AND result_binding_digest IS NOT NULL) + ) + ) + OR + ( + status IN ('APPLIED', 'REJECTED') + AND result_commit_id IS NOT NULL + AND result_binding_digest IS NOT NULL + AND result_identity IS NOT NULL + AND result_bytes IS NOT NULL + AND applied_units_json IS NOT NULL + AND jsonb_typeof(applied_units_json::jsonb) = 'array' + AND (status <> 'REJECTED' OR applied_units_json::jsonb = '[]'::jsonb) + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_result_digest CHECK ( + result_binding_digest IS NULL OR result_binding_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_owner_result_identity CHECK ( + result_identity IS NULL OR ( + char_length(result_identity) BETWEEN 1 AND 512 + AND result_identity !~ '^[[:space:]]*$' + ) + ) +); + +CREATE TABLE game_design_draft_commit_visibility_fence ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + result_vector_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility_fence PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_visibility_vector CHECK ( + jsonb_typeof(result_vector_json::jsonb) = 'array' + ) +); + +CREATE TABLE game_design_draft_commit_visibility ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_pointer_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE game_design_draft_commit_application_slot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_application_slot PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_application_slot_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT +); + +CREATE TABLE game_design_draft_commit_final_abort ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + abort_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_final_abort PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_final_abort_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_final_abort_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_binding CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_bytes CHECK (octet_length(abort_bytes) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_commit_has_exact_terminal_abort_vector( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_count INTEGER; + actual_count INTEGER; +BEGIN + SELECT input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request + AND commit_id = target_commit; + IF NOT FOUND THEN + RETURN FALSE; + END IF; + IF jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' + OR jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners') = 0 THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + SELECT count(*) INTO actual_count + FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request; + IF actual_count <> expected_count THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = target_tenant + AND outcome.canonical_version_id = target_version + AND outcome.request_id = target_request + AND outcome.owner = required.owner + WHERE outcome.owner IS NULL + OR outcome.status NOT IN ('APPLIED', 'REJECTED') + OR outcome.result_commit_id IS DISTINCT FROM target_commit + OR outcome.result_binding_digest IS DISTINCT FROM parent_record.input_digest + OR outcome.result_identity IS NULL + OR outcome.result_bytes IS NULL + OR outcome.applied_units_json IS NULL + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_commit_final_abort() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence is immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json, workflow_state + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.binding_json + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Final-abort evidence must bind the exact active Draft commit' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'A successful Draft visibility fence cannot be final-aborted' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT gd_draft_commit_has_exact_terminal_abort_vector( + NEW.canonical_tenant_id, + NEW.canonical_version_id, + NEW.request_id, + NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-abort evidence requires every exact owner result to be terminal' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_final_abort + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_final_abort(); + +CREATE FUNCTION reject_gd_draft_commit_final_abort_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_final_abort) THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_final_abort + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_final_abort_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_binding() RETURNS trigger AS $$ +DECLARE + version_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft commit bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.game_design_version_row_id IS DISTINCT FROM OLD.game_design_version_row_id + OR NEW.game_design_version_tenant_key IS DISTINCT FROM OLD.game_design_version_tenant_key + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.base_commit_id IS DISTINCT FROM OLD.base_commit_id + OR NEW.input_digest IS DISTINCT FROM OLD.input_digest + OR NEW.binding_json IS DISTINCT FROM OLD.binding_json + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft commit binding identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.workflow_state IS DISTINCT FROM OLD.workflow_state THEN + IF OLD.workflow_state IN ('SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION') + OR NOT ( + (OLD.workflow_state = 'QUEUED' + AND NEW.workflow_state = 'APPLYING') + OR (OLD.workflow_state = 'APPLYING' + AND NEW.workflow_state IN ( + 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', 'REJECTED', + 'FAILED_NONPUBLICATION' + )) + OR (OLD.workflow_state = 'RECONCILIATION_REQUIRED' + AND NEW.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + )) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft commit workflow transition' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'An unchanged Draft commit workflow state is not rewritten' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'REJECTED' + AND ( + EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) + OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) + ) THEN + RAISE EXCEPTION 'Unresolved or applied Draft owner outcomes cannot be finalized REJECTED' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'FAILED_NONPUBLICATION' + AND ( + NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = OLD.input_digest + AND abort.binding_json = OLD.binding_json + ) + OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) + ) THEN + RAISE EXCEPTION 'Failed nonpublication requires exact final-abort evidence and no visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.binding_json::jsonb ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.binding_json::jsonb ->> 'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id + OR NEW.binding_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its indexed identity' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + ) INTO version_matches; + IF NOT version_matches THEN + RAISE EXCEPTION 'Draft commit target lacks exact canonical Game Design Version source proof' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_binding(); + +CREATE FUNCTION reject_gd_draft_commit_binding_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit) THEN + RAISE EXCEPTION 'Game Design Draft commit bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_binding_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_owner_result() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft owner results are retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design Draft owner result has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF NOT ((parent_record.binding_json::jsonb -> 'requiredOwners') ? NEW.owner) THEN + RAISE EXCEPTION 'Game Design Draft owner result is outside the bound required owner set' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'NOT_ATTEMPTED' + OR NEW.result_commit_id IS NOT NULL + OR NEW.result_binding_digest IS NOT NULL + OR NEW.result_identity IS NOT NULL + OR NEW.result_bytes IS NOT NULL + OR NEW.applied_units_json IS NOT NULL THEN + RAISE EXCEPTION 'Draft commit owner result must begin NOT_ATTEMPTED without evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.owner IS DISTINCT FROM OLD.owner + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft owner result identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status = OLD.status THEN + IF NEW.result_commit_id IS DISTINCT FROM OLD.result_commit_id + OR NEW.result_binding_digest IS DISTINCT FROM OLD.result_binding_digest + OR NEW.result_identity IS DISTINCT FROM OLD.result_identity + OR NEW.result_bytes IS DISTINCT FROM OLD.result_bytes + OR NEW.applied_units_json IS DISTINCT FROM OLD.applied_units_json + OR NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'Exact Draft owner result retries do not rewrite persisted evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NOT ( + (OLD.status = 'NOT_ATTEMPTED' AND NEW.status = 'IN_PROGRESS') + OR (OLD.status = 'IN_PROGRESS' AND NEW.status IN ('APPLIED', 'REJECTED', 'UNKNOWN')) + OR (OLD.status = 'UNKNOWN' AND NEW.status IN ('APPLIED', 'REJECTED')) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft owner result transition' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status IN ('APPLIED', 'REJECTED') + AND (NEW.result_commit_id IS DISTINCT FROM parent_record.commit_id + OR NEW.result_binding_digest IS DISTINCT FROM parent_record.input_digest) THEN + RAISE EXCEPTION 'Game Design Draft owner result does not match its exact commit binding' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_owner_result + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_owner_result + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_owner_result(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_fence() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft visibility fences are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, workflow_state, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.commit_id IS DISTINCT FROM NEW.commit_id + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Draft visibility fence lacks a matching nonterminal commit binding' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-aborted Draft commits cannot gain a visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Draft visibility fence requires every exact required owner to be APPLIED' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_visibility_fence + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_fence(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_fence_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence) THEN + RAISE EXCEPTION 'Game Design Draft visibility fences cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_visibility_fence + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_visibility_fence_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_pointer() RETURNS trigger AS $$ +DECLARE + fence_digest VARCHAR(71); + workflow_state VARCHAR(32); +BEGIN + SELECT f.input_digest, c.workflow_state INTO fence_digest, workflow_state + FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = f.canonical_tenant_id + AND c.canonical_version_id = f.canonical_version_id + AND c.request_id = f.request_id + AND c.commit_id = f.commit_id + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id; + IF NOT FOUND OR fence_digest IS DISTINCT FROM NEW.input_digest + OR workflow_state = 'FAILED_NONPUBLICATION' + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Draft visibility pointer must name its exact durable fence' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer + BEFORE INSERT OR UPDATE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_pointer(); + +CREATE FUNCTION enforce_gd_draft_commit_application_slot() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + SELECT workflow_state, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = OLD.canonical_tenant_id + AND canonical_version_id = OLD.canonical_version_id + AND request_id = OLD.request_id + AND commit_id = OLD.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Draft application slot has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.workflow_state = 'SYNCHRONIZED' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + AND f.input_digest = parent_record.input_digest + ) OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = OLD.canonical_tenant_id + AND outcome.canonical_version_id = OLD.canonical_version_id + AND outcome.request_id = OLD.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Synchronized Draft application slot requires its exact complete fence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'REJECTED' THEN + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) THEN + RAISE EXCEPTION 'Rejected Draft application slot cannot hide unresolved or applied owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'FAILED_NONPUBLICATION' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = parent_record.input_digest + AND abort.binding_json = parent_record.binding_json + ) OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) THEN + RAISE EXCEPTION 'Failed nonpublication slot release requires exact abort proof and terminal owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Draft application slot cannot be released before a terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design Draft application slot identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT workflow_state INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND OR parent_record.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + ) THEN + RAISE EXCEPTION 'Draft application slot requires an exact nonterminal commit' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_application_slot + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_application_slot(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql new file mode 100644 index 0000000000..a1496e12a2 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql @@ -0,0 +1,265 @@ +CREATE TABLE game_design_authored_draft_publish_selection ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + publish_request_id VARCHAR(1024) NOT NULL, + version_state_epoch BIGINT NOT NULL, + selected_commit_request_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + selected_commit_digest VARCHAR(71) NOT NULL, + selection_digest VARCHAR(71) NOT NULL, + selection_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_authored_draft_publish_selection PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT uq_gd_authored_draft_publish_selection_request UNIQUE ( + canonical_tenant_id, + canonical_version_id, + publish_request_id + ), + CONSTRAINT fk_gd_authored_draft_publish_selection_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_authored_draft_publish_selection_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND char_length(publish_request_id) BETWEEN 1 AND 1024 + AND publish_request_id !~ '^[[:space:]]*$' + AND publish_request_id !~ ':' + AND version_state_epoch > 0 + AND selected_commit_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_digests CHECK ( + selected_commit_digest ~ '^sha256:[0-9a-f]{64}$' + AND selection_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_json CHECK ( + jsonb_typeof(selection_json::jsonb) = 'object' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_draft_publish_selection() RETURNS trigger AS $$ +DECLARE + version_record RECORD; + commit_record RECORD; + current_fence RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Authored Draft publication selections are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'publishRequestId' + IS DISTINCT FROM NEW.publish_request_id + OR NEW.selection_json::jsonb -> 'intent' ->> 'expectedVersionStateEpoch' + IS DISTINCT FROM NEW.version_state_epoch::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitRequestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its complete caller intent' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'target' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_state, v.version_state_epoch, v.is_script_only, + v.script_patch_version, v.base_version_id + INTO version_record + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND v.version_state = 'DRAFT' + AND v.version_state_epoch = NEW.version_state_epoch + AND v.version_state_epoch > 0 + AND v.is_script_only = FALSE + AND v.script_patch_version IS NULL + AND v.base_version_id IS NULL + FOR UPDATE OF v; + IF NOT FOUND THEN + RAISE EXCEPTION 'Authored Draft publication selection lacks an exact current full Draft Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Active or unresolved owner application prevents Draft publication selection' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT c.commit_id, c.input_digest, c.binding_json, c.workflow_state + INTO commit_record + FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.selected_commit_request_id + AND c.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR commit_record.workflow_state <> 'SYNCHRONIZED' + OR commit_record.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitDigest' + IS DISTINCT FROM commit_record.input_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitBindingJson' + IS DISTINCT FROM commit_record.binding_json THEN + RAISE EXCEPTION 'Selected authored Draft commit is missing or differs from exact durable binding' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'requestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'commitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'inputDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from exact synchronized fence identity' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT f.input_digest, f.result_vector_json + INTO current_fence + FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.selected_commit_request_id + AND f.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR current_fence.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'resultVectorJson' + IS DISTINCT FROM current_fence.result_vector_json THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from the exact immutable result fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.request_id = NEW.selected_commit_request_id + AND v.commit_id = NEW.selected_commit_id + AND v.input_digest = NEW.selected_commit_digest + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit is stale relative to current synchronized visibility' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(commit_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.selected_commit_request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit lacks every required APPLIED owner outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_authored_draft_publish_selection + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_draft_publish_selection + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_authored_draft_publish_selection(); + +CREATE FUNCTION reject_gd_draft_application_during_authored_publication() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Authored Draft publication reservation prevents later owner application' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_application_authored_publication_interlock + BEFORE INSERT ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION reject_gd_draft_application_during_authored_publication(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql new file mode 100644 index 0000000000..6ea648cf2f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql @@ -0,0 +1,5 @@ +-- A publication operation selects one exact Version in its canonical tenant. +-- Conflicting retained reservations deliberately fail migration; no history is discarded. +ALTER TABLE game_design_authored_draft_publish_selection + ADD CONSTRAINT uq_gd_authored_draft_publish_operation + UNIQUE (canonical_tenant_id, publish_request_id); diff --git a/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql new file mode 100644 index 0000000000..5f3b79686d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql @@ -0,0 +1,5 @@ +-- Full-version attempts retain the exact authored-Draft selection digest, +-- including its algorithm prefix. Widen only; preserve every existing attempt +-- and its original request digest, including absent historical evidence. +ALTER TABLE publish_attempt + ALTER COLUMN request_digest TYPE VARCHAR(71); diff --git a/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql b/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql new file mode 100644 index 0000000000..6558e157d0 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql @@ -0,0 +1,405 @@ +-- Account-bound Game Design terminal readback is retained independently of coordinator workflow +-- status. Existing V42 rows are deliberately not backfilled: status-only history is not a receipt. +CREATE TABLE game_design_draft_terminal_operation ( + operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + fence_id UUID NOT NULL, + actor_account_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + expected_draft_epoch TEXT NOT NULL, + account_binding_bytes BYTEA NOT NULL, + account_binding_digest VARCHAR(71) NOT NULL, + game_design_binding_json TEXT NOT NULL, + game_design_input_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gd_draft_terminal_operation_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT uq_gd_draft_terminal_operation_fence UNIQUE (fence_id), + CONSTRAINT fk_gd_draft_terminal_operation_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_terminal_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND actor_account_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + AND expected_draft_epoch ~ '^(0|[1-9][0-9]*)$' + AND octet_length(account_binding_bytes) > 0 + ), + CONSTRAINT chk_gd_draft_terminal_operation_digests CHECK ( + account_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_design_input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_terminal_operation_binding CHECK ( + jsonb_typeof(game_design_binding_json::jsonb) = 'object' + ) +); + +CREATE TABLE game_design_draft_terminal_outcome ( + operation_id UUID NOT NULL, + outcome VARCHAR(32) NOT NULL, + owner_result_vector_json TEXT NOT NULL, + terminal_evidence_bytes BYTEA NOT NULL, + terminal_evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_outcome PRIMARY KEY (operation_id), + CONSTRAINT fk_gd_draft_terminal_outcome_operation FOREIGN KEY (operation_id) + REFERENCES game_design_draft_terminal_operation (operation_id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_terminal_outcome_kind CHECK ( + outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED') + ), + CONSTRAINT chk_gd_draft_terminal_outcome_evidence CHECK ( + octet_length(terminal_evidence_bytes) > 0 + AND terminal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND jsonb_typeof(owner_result_vector_json::jsonb) = 'array' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_terminal_vector_matches_owner_results( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID, + vector_json TEXT +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_count INTEGER; +BEGIN + SELECT input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request + AND commit_id = target_commit; + IF NOT FOUND THEN + RETURN FALSE; + END IF; + IF jsonb_typeof(vector_json::jsonb) IS DISTINCT FROM 'array' + OR jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + IF jsonb_array_length(vector_json::jsonb) <> expected_count THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + WHERE NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(vector_json::jsonb) actual + JOIN game_design_draft_commit_owner_result stored + ON stored.canonical_tenant_id = target_tenant + AND stored.canonical_version_id = target_version + AND stored.request_id = target_request + AND stored.owner = required.owner + WHERE actual ->> 'owner' = required.owner + AND actual ->> 'status' = stored.status + AND actual ->> 'commitId' = stored.result_commit_id::text + AND actual ->> 'bindingDigest' = stored.result_binding_digest + AND actual ->> 'resultIdentity' = stored.result_identity + AND actual ->> 'resultBytesBase64' = replace(encode(stored.result_bytes, 'base64'), E'\n', '') + AND actual -> 'appliedEpochs' = stored.applied_units_json::jsonb + ) + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_terminal_operation() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Account operation bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT input_digest, binding_json, workflow_state + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account operation must claim an existing Game Design commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.input_digest IS DISTINCT FROM NEW.game_design_input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.game_design_binding_json + OR parent_record.workflow_state IS DISTINCT FROM 'QUEUED' + OR NEW.game_design_binding_json::jsonb ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.game_design_binding_json::jsonb ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.game_design_binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.game_design_binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.game_design_binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id THEN + RAISE EXCEPTION 'Account operation must claim the exact queued Game Design binding before dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 + FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id + AND slot.canonical_version_id = NEW.canonical_version_id + ) OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_owner_result owner_result + WHERE owner_result.canonical_tenant_id = NEW.canonical_tenant_id + AND owner_result.canonical_version_id = NEW.canonical_version_id + AND owner_result.request_id = NEW.request_id + AND owner_result.status <> 'NOT_ATTEMPTED' + ) THEN + RAISE EXCEPTION 'Account operation binding was not retained before owner dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM version v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.version_state = 'DRAFT' + ) THEN + RAISE EXCEPTION 'Account operation can be claimed only for the exact DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_operation + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_operation(); + +CREATE FUNCTION reject_gd_draft_terminal_operation_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_operation) THEN + RAISE EXCEPTION 'Game Design Account operation bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_operation + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_operation_truncate(); + +CREATE FUNCTION enforce_gd_draft_terminal_outcome() RETURNS trigger AS $$ +DECLARE + operation_record RECORD; + commit_record RECORD; + fence_record RECORD; + abort_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design terminal outcomes are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * + INTO operation_record + FROM game_design_draft_terminal_operation + WHERE operation_id = NEW.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact Account operation binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + SELECT workflow_state, input_digest, binding_json + INTO commit_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact coordinator commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF NOT gd_draft_terminal_vector_matches_owner_results( + operation_record.canonical_tenant_id, + operation_record.canonical_version_id, + operation_record.request_id, + operation_record.commit_id, + NEW.owner_result_vector_json + ) THEN + RAISE EXCEPTION 'Terminal outcome requires the complete exact retained owner result vector' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.outcome = 'COMMITTED' THEN + SELECT input_digest, result_vector_json + INTO fence_record + FROM game_design_draft_commit_visibility_fence + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Committed terminal outcome lacks its exact visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'SYNCHRONIZED' + OR fence_record.input_digest IS DISTINCT FROM operation_record.game_design_input_digest + OR fence_record.result_vector_json IS DISTINCT FROM NEW.owner_result_vector_json + OR NEW.terminal_evidence_bytes IS DISTINCT FROM convert_to(NEW.owner_result_vector_json, 'UTF8') + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Committed terminal outcome must match synchronized visibility and every APPLIED owner' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.outcome = 'DEFINITIVELY_ABORTED' THEN + SELECT abort_bytes + INTO abort_record + FROM game_design_draft_commit_final_abort + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Aborted terminal outcome lacks its exact final-abort tombstone' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'FAILED_NONPUBLICATION' + OR abort_record.abort_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_visibility_fence fence + WHERE fence.canonical_tenant_id = operation_record.canonical_tenant_id + AND fence.canonical_version_id = operation_record.canonical_version_id + AND fence.request_id = operation_record.request_id + AND fence.commit_id = operation_record.commit_id + ) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' NOT IN ('APPLIED', 'REJECTED') + ) THEN + RAISE EXCEPTION 'Aborted terminal outcome must match exact final-abort evidence and definitive participants' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Unknown Game Design terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_outcome + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_outcome(); + +CREATE FUNCTION reject_gd_draft_terminal_outcome_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_outcome) THEN + RAISE EXCEPTION 'Game Design terminal outcomes cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_outcome + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_outcome_truncate(); + +CREATE FUNCTION require_gd_draft_account_terminal_readback() RETURNS trigger AS $$ +DECLARE + current_commit RECORD; + operation_record RECORD; + terminal_record RECORD; + expected_outcome VARCHAR(32); +BEGIN + SELECT workflow_state, canonical_tenant_id, canonical_version_id, request_id, commit_id + INTO current_commit + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + IF current_commit.workflow_state NOT IN ('SYNCHRONIZED', 'FAILED_NONPUBLICATION', 'REJECTED') THEN + RETURN NULL; + END IF; + + SELECT operation_id + INTO operation_record + FROM game_design_draft_terminal_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + + IF current_commit.workflow_state = 'REJECTED' THEN + RAISE EXCEPTION 'Account-bound rejection is not a terminal readback; exact final-abort evidence is required' + USING ERRCODE = 'check_violation'; + END IF; + + expected_outcome := + CASE current_commit.workflow_state + WHEN 'SYNCHRONIZED' THEN 'COMMITTED' + ELSE 'DEFINITIVELY_ABORTED' + END; + SELECT outcome + INTO terminal_record + FROM game_design_draft_terminal_outcome + WHERE operation_id = operation_record.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + IF terminal_record.outcome IS DISTINCT FROM expected_outcome THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER trg_gd_draft_account_terminal_readback + AFTER UPDATE ON game_design_draft_commit + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION require_gd_draft_account_terminal_readback(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql new file mode 100644 index 0000000000..4b7d6eb4c7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql @@ -0,0 +1,238 @@ +-- Retained attestations keep their original schema and bytes; no selector is inferred or backfilled. +ALTER TABLE published_release_bundle + ADD COLUMN world_published_start_location_evidence_json TEXT; + +-- This adds an insertion guard beside (and does not replace) the existing immutable row/source guards. +-- Payload decoding checks storage relations, not authenticated World producer provenance. +-- [jooq ignore start] +-- The retained Account and World operation use big-endian byte-length frames. +CREATE FUNCTION published_world_selector_frame(payload BYTEA, wanted INTEGER) RETURNS BYTEA AS $$ +DECLARE + offset_bytes INTEGER := 0; + frame_index INTEGER := 0; + frame_length BIGINT; +BEGIN + WHILE offset_bytes < octet_length(payload) LOOP + IF offset_bytes + 4 > octet_length(payload) THEN + RAISE EXCEPTION 'truncated published World evidence frame' USING ERRCODE = 'check_violation'; + END IF; + frame_length := get_byte(payload, offset_bytes)::BIGINT * 16777216 + + get_byte(payload, offset_bytes + 1)::BIGINT * 65536 + + get_byte(payload, offset_bytes + 2)::BIGINT * 256 + get_byte(payload, offset_bytes + 3); + offset_bytes := offset_bytes + 4; + IF frame_length > octet_length(payload) - offset_bytes THEN + RAISE EXCEPTION 'invalid published World evidence frame length' USING ERRCODE = 'check_violation'; + END IF; + IF frame_index = wanted THEN + RETURN substring(payload FROM offset_bytes + 1 FOR frame_length::INTEGER); + END IF; + offset_bytes := offset_bytes + frame_length::INTEGER; + frame_index := frame_index + 1; + END LOOP; + RAISE EXCEPTION 'missing published World evidence frame' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version <> 'v2' THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'release v2 requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'release v2 World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'release v2 requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'release v2 requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'release v2 owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'release v2 selector differs from original selected APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'release v2 requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',3),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',1)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'release v2 has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'release v2 participant differs from selected commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_world_start_location_evidence + BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION enforce_published_world_start_location_evidence(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql new file mode 100644 index 0000000000..056e74b3a5 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql @@ -0,0 +1,180 @@ +ALTER TABLE publish_attempt ADD COLUMN revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0); + +CREATE TABLE game_design_publication_operation ( + publish_workflow_id VARCHAR(1024) PRIMARY KEY REFERENCES publish_attempt(publish_workflow_id) ON DELETE RESTRICT, + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL REFERENCES version(id) ON DELETE RESTRICT, + selection_digest VARCHAR(71) NOT NULL, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + outcome TEXT NOT NULL DEFAULT 'PENDING' CHECK (outcome IN ('PENDING', 'PUBLISHED', 'NO_PUBLICATION')), + revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0), + result_bytes BYTEA, + release_row_json TEXT, + CHECK ((outcome = 'PENDING') = (result_bytes IS NULL)), + CHECK ((outcome = 'PUBLISHED') = (release_row_json IS NOT NULL)), + UNIQUE (tenant_id, version_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_design_publication_operation() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + account_bytes BYTEA; input_bytes BYTEA; world_json JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'publication operation history is immutable' USING ERRCODE = 'check_violation'; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id; + account_bytes := published_world_selector_frame(NEW.request_bytes, 1); + input_bytes := published_world_selector_frame(account_bytes, 3); + world_json := convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB; + IF convert_from(published_world_selector_frame(NEW.request_bytes, 0), 'UTF8') <> 'game-design-publication-operation/v1' + OR convert_from(published_world_selector_frame(account_bytes, 0), 'UTF8') <> 'account-publication-authorization/v1' + OR convert_from(published_world_selector_frame(input_bytes, 0), 'UTF8') <> 'account-publication-input/v1' + OR published_world_selector_frame(input_bytes, 2) IS DISTINCT FROM convert_to(selected.selection_json, 'UTF8') + OR convert_from(published_world_selector_frame(input_bytes, 3), 'UTF8') IS DISTINCT FROM selected.selection_digest + OR world_json->'request'->>'requestDigest' IS DISTINCT FROM substring(selected.selection_digest FROM 8) + OR world_json->'request'->>'canonicalTenantId' IS DISTINCT FROM selected.canonical_tenant_id::TEXT + OR world_json->'request'->>'canonicalVersionId' IS DISTINCT FROM selected.canonical_version_id::TEXT + OR world_json->'request'->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR world_json->'request'->>'publicationRequestId' IS DISTINCT FROM selected.publish_request_id + OR world_json->'request'->>'versionStateEpoch' IS DISTINCT FROM selected.version_state_epoch::TEXT THEN + RAISE EXCEPTION 'publication operation bytes differ from exact owner selection' USING ERRCODE = 'check_violation'; + END IF; + IF attempt.tenant_id <> NEW.tenant_id OR attempt.version_id <> NEW.version_id + OR attempt.publish_type <> 'FULL_VERSION' OR attempt.request_digest IS DISTINCT FROM NEW.selection_digest + OR NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.game_design_version_tenant_key = NEW.tenant_id + AND s.game_design_version_row_id = NEW.version_id AND s.selection_digest = NEW.selection_digest) THEN + RAISE EXCEPTION 'publication operation does not bind exact selected attempt' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.outcome <> 'PENDING' OR NEW.revision <> 1 OR attempt.status <> 'PENDING' + OR EXISTS (SELECT 1 FROM published_release_bundle WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id) THEN + RAISE EXCEPTION 'historical attempts cannot acquire publication authority' USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF OLD.outcome <> 'PENDING' OR NEW.outcome = 'PENDING' + OR NEW.revision <> OLD.revision + 1 + OR (NEW.publish_workflow_id, NEW.tenant_id, NEW.version_id, NEW.selection_digest, NEW.request_bytes) + IS DISTINCT FROM (OLD.publish_workflow_id, OLD.tenant_id, OLD.version_id, OLD.selection_digest, OLD.request_bytes) THEN + RAISE EXCEPTION 'publication operation identity or terminal outcome is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_design_publication_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_game_design_publication_operation(); + +CREATE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version <> 'v2' AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version <> 'v2' + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER selected_publication_release_guard BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION guard_selected_publication_release(); + +CREATE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT to_jsonb(r)::TEXT INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_operation_commit_guard AFTER INSERT OR UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_release_commit_guard AFTER INSERT + ON published_release_bundle DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_attempt_commit_guard AFTER UPDATE + ON publish_attempt DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); + +CREATE FUNCTION guard_publish_attempt_revision() RETURNS trigger AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.revision <> OLD.revision + 1 + OR (NEW.id, NEW.tenant_id, NEW.publish_workflow_id, NEW.publish_type, NEW.version_id, + NEW.version_number, NEW.script_patch_version, NEW.base_version_id, NEW.created_at) + IS DISTINCT FROM (OLD.id, OLD.tenant_id, OLD.publish_workflow_id, OLD.publish_type, OLD.version_id, + OLD.version_number, OLD.script_patch_version, OLD.base_version_id, OLD.created_at) + OR (NEW.request_digest IS DISTINCT FROM OLD.request_digest AND + (OLD.request_digest IS NOT NULL OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = OLD.tenant_id AND game_design_version_row_id = OLD.version_id))) THEN + RAISE EXCEPTION 'publish attempt is stale or terminal' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publish_attempt_revision_guard BEFORE UPDATE ON publish_attempt + FOR EACH ROW EXECUTE FUNCTION guard_publish_attempt_revision(); + +CREATE FUNCTION guard_sealed_candidate_admission() RETURNS trigger AS $$ +BEGIN + -- Private puts already in flight may finish; this guards admission/retained candidate changes, + -- not cancellation, reachability, abandonment, deletion, or distributed object-store writes. + IF NEW.artifact_state = 'STAGED' AND EXISTS (SELECT 1 FROM game_design_publication_operation + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id AND outcome <> 'PENDING') THEN + RAISE EXCEPTION 'sealed publication refuses candidate admission' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER sealed_candidate_admission_guard BEFORE INSERT OR UPDATE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_sealed_candidate_admission(); + +CREATE FUNCTION forbid_publication_operation_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'publication operation history cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_operation_no_truncate BEFORE TRUNCATE ON game_design_publication_operation + FOR EACH STATEMENT EXECUTE FUNCTION forbid_publication_operation_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql new file mode 100644 index 0000000000..a40cd4fd14 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql @@ -0,0 +1,141 @@ +-- Retained V50 terminal rows keep their original bytes and gain no unverifiable epoch. +ALTER TABLE game_design_publication_operation ADD COLUMN terminal_evidence_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN publication_version_state_epoch BIGINT; +ALTER TABLE game_design_publication_operation ADD COLUMN release_content_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN published_release_bundle_digest VARCHAR(71); +ALTER TABLE game_design_publication_operation ADD CONSTRAINT publication_terminal_extension_shape CHECK ( + (terminal_evidence_bytes IS NULL AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (terminal_evidence_bytes IS NOT NULL AND octet_length(terminal_evidence_bytes) > 0 AND + ((outcome = 'NO_PUBLICATION' AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (outcome = 'PUBLISHED' AND publication_version_state_epoch IS NOT NULL AND publication_version_state_epoch > 0 + AND release_content_bytes IS NOT NULL AND octet_length(release_content_bytes) > 0 + AND published_release_bundle_digest IS NOT NULL AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$')))); + +-- [jooq ignore start] +-- ADR byte-length framing for complete immutable release content, distinct from launch evidence. +CREATE FUNCTION publication_content_frame(value BYTEA) RETURNS BYTEA AS $$ + SELECT convert_to(octet_length(value)::TEXT || ':', 'UTF8') || value; +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_text(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_frame(convert_to(value, 'UTF8')); +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_optional(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_text(CASE WHEN value IS NULL THEN 'false' ELSE 'true' END) + || publication_content_text(COALESCE(value, '')); +$$ LANGUAGE SQL IMMUTABLE; +CREATE FUNCTION publication_content_strings(values_json JSONB) RETURNS BYTEA AS $$ +DECLARE result BYTEA; value JSONB; +BEGIN + result := publication_content_text(jsonb_array_length(values_json)::TEXT); + FOR value IN SELECT * FROM jsonb_array_elements(values_json) LOOP + result := result || publication_content_text(value #>> '{}'); + END LOOP; + RETURN result; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version <> 'v2' THEN + RAISE EXCEPTION 'terminal publication requires complete full-version v2 content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; + +CREATE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR to_jsonb(release)::TEXT IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_terminal_extension_guard BEFORE INSERT OR UPDATE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_publication_terminal_extension(); + +CREATE FUNCTION verify_publication_terminal_epoch_commit() RETURNS trigger AS $$ +BEGIN + IF NEW.outcome = 'PUBLISHED' AND NEW.terminal_evidence_bytes IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + AND version_state = 'PUBLISHED' AND version_state_epoch = NEW.publication_version_state_epoch) THEN + RAISE EXCEPTION 'publication terminal epoch lacks its exact atomic Version commit' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_terminal_epoch_commit_guard AFTER UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_terminal_epoch_commit(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql b/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql new file mode 100644 index 0000000000..c391045127 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql @@ -0,0 +1,311 @@ +-- Explicit new-Draft genesis requires the Version's actual insertion transaction witness. +-- No retained backfill or inferred empty baseline is installed. +CREATE TABLE game_design_realm_policy_version_insert ( + version_id BIGINT PRIMARY KEY REFERENCES version (id), + creation_transaction_id TEXT NOT NULL CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_realm_policy_genesis ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + receipt_id UUID NOT NULL UNIQUE, + version_id BIGINT NOT NULL UNIQUE REFERENCES game_design_realm_policy_version_insert (version_id), + creation_transaction_id TEXT NOT NULL, + receipt_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000') +); + +CREATE TABLE game_design_realm_policy_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + snapshot_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence + (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- PostgreSQL JSON extraction is unsupported by the jOOQ DDL simulation; retain the exact owner checks. +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_snapshot + ADD CONSTRAINT realm_policy_snapshot_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_snapshot_epoch CHECK (snapshot_json::JSONB->>'sourceEpoch' ~ '^(0|[1-9][0-9]*)$'), + ADD CONSTRAINT realm_policy_snapshot_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_source ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (visible_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +CREATE TABLE game_design_realm_policy_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + owner_result_bytes BYTEA, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (inherited_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_application + ADD CONSTRAINT realm_policy_application_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_application_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION witness_realm_policy_version_insert() RETURNS trigger AS $$ +BEGIN + IF NEW.canonical_tenant_id IS NOT NULL AND NEW.canonical_version_id IS NOT NULL + AND NEW.version_state = 'DRAFT' AND NOT NEW.is_script_only + AND NEW.script_patch_version IS NULL AND NEW.base_version_id IS NULL THEN + INSERT INTO game_design_realm_policy_version_insert (version_id, creation_transaction_id) + VALUES (NEW.id, pg_current_xact_id()::TEXT); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_witness AFTER INSERT ON version + FOR EACH ROW EXECUTE FUNCTION witness_realm_policy_version_insert(); + +CREATE FUNCTION guard_realm_policy_genesis() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; witness game_design_realm_policy_version_insert%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'new-Draft insertion and genesis evidence is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_version_insert' THEN + IF pg_trigger_depth() < 2 OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'new-Draft witness requires the actual Version insertion trigger' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT owner_version FROM version WHERE id = NEW.version_id FOR UPDATE; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert WHERE version_id = NEW.version_id; + IF witness.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.creation_transaction_id <> witness.creation_transaction_id + OR NEW.canonical_tenant_id <> owner_version.canonical_tenant_id + OR NEW.canonical_version_id <> owner_version.canonical_version_id + OR owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL + OR EXISTS (SELECT 1 FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) + OR NEW.receipt_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-realm-policy-genesis/v1' + OR NEW.receipt_json::JSONB->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR NEW.receipt_json::JSONB->>'creationTransactionId' IS DISTINCT FROM witness.creation_transaction_id + OR NEW.receipt_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM owner_version.canonical_tenant_id::TEXT + OR NEW.receipt_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM owner_version.canonical_version_id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.receipt_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.receipt_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.receipt_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'realm policy genesis lacks the exact fresh owner insertion' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_version_insert + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); +CREATE TRIGGER realm_policy_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_genesis + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); + +CREATE FUNCTION guard_realm_policy_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; operation game_design_publication_operation%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + expected BYTEA; payload BYTEA; policies JSONB; source_binding game_design_draft_commit%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'realm policy source history cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT owner_version FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'realm policy source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF TG_TABLE_NAME = 'game_design_realm_policy_application' THEN + IF OLD.owner_result_bytes IS NOT NULL OR NEW.owner_result_bytes IS NULL + OR (to_jsonb(NEW) - 'owner_result_bytes') IS DISTINCT FROM (to_jsonb(OLD) - 'owner_result_bytes') THEN + RAISE EXCEPTION 'realm policy application permits only its one atomic complete owner result' USING ERRCODE = 'check_violation'; + END IF; + ELSIF TG_TABLE_NAME <> 'game_design_realm_policy_source' THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + ELSIF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF EXISTS (SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'realm policy source is frozen' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_source' THEN + IF TG_OP = 'INSERT' AND NEW.genesis_receipt_id IS NOT NULL THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_genesis g WHERE g.receipt_id = NEW.genesis_receipt_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id AND g.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'genesis source must begin empty at its exact owner epoch zero' USING ERRCODE = 'check_violation'; + END IF; + END IF; + END IF; + IF TG_TABLE_NAME IN ('game_design_realm_policy_snapshot', 'game_design_realm_policy_application') THEN + SELECT * INTO STRICT source_binding FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + policies := NEW.snapshot_json::JSONB->'policies'; + IF NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM source_binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM source_binding.input_digest + OR jsonb_typeof(policies) IS DISTINCT FROM 'array' + OR jsonb_array_length(policies) NOT BETWEEN 0 AND 128 + OR (SELECT count(DISTINCT p->'policy'->>'realmSlug') FROM jsonb_array_elements(policies) p) <> jsonb_array_length(policies) THEN + RAISE EXCEPTION 'realm policy snapshot lacks exact source binding or unique bounded selectors' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + policies := snapshot.snapshot_json::JSONB->'policies'; + IF jsonb_array_length(policies) NOT BETWEEN 1 AND 128 + OR (SELECT count(*) FROM jsonb_array_elements(policies) p WHERE p->'policy'->'visible' = 'true'::JSONB + AND p->'policy'->'publicProduction' = 'true'::JSONB) <> 1 + OR operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.visible_commit_id = NEW.commit_id + AND s.source_epoch = snapshot.snapshot_json::JSONB->>'sourceEpoch') + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility v WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id AND v.commit_id = NEW.commit_id) THEN + RAISE EXCEPTION 'realm policy capture differs from original synchronized publication' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-realm-policy-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload + || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'realm policy capture bytes differ from immutable source' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER realm_policy_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_source_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_source + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_application + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_capture + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); + +CREATE FUNCTION verify_realm_policy_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; result game_design_draft_commit_owner_result%ROWTYPE; + expected BYTEA; payload BYTEA; application game_design_realm_policy_application%ROWTYPE; genesis game_design_realm_policy_genesis%ROWTYPE; +BEGIN + SELECT * INTO STRICT application FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT binding FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT result FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + payload := convert_to('game-design-realm-policy-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.genesis_receipt_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := ''::BYTEA; + IF NEW.genesis_receipt_id IS NOT NULL THEN + SELECT * INTO STRICT genesis FROM game_design_realm_policy_genesis WHERE receipt_id = NEW.genesis_receipt_id; + IF genesis.canonical_tenant_id <> NEW.canonical_tenant_id OR genesis.canonical_version_id <> NEW.canonical_version_id THEN + RAISE EXCEPTION 'policy application changed genesis target' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to(genesis.receipt_json, 'UTF8'); + END IF; + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.inherited_commit_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(COALESCE(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF result.status <> 'APPLIED' OR application.owner_result_bytes IS NULL + OR result.result_bytes IS DISTINCT FROM application.owner_result_bytes OR NEW.result_bytes IS DISTINCT FROM expected + OR result.result_commit_id <> NEW.commit_id OR result.result_binding_digest <> binding.input_digest + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM binding.input_digest + OR (NEW.snapshot_json::JSONB->>'sourceEpoch')::NUMERIC <> NEW.expected_epoch::NUMERIC + 1 THEN + RAISE EXCEPTION 'realm policy application lacks atomic exact coordinator result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER realm_policy_application_commit_guard AFTER INSERT ON game_design_realm_policy_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_realm_policy_application_commit(); + +CREATE FUNCTION deny_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'realm policy owner evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_snapshot_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_source_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_source + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_application_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_capture_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_version_insert_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_version_insert + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_genesis_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_genesis + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql new file mode 100644 index 0000000000..80a635e3f7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql @@ -0,0 +1,278 @@ +CREATE TABLE game_design_published_realm_policy_set ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL CHECK (game_design_version_row_id > 0), + version_number INTEGER NOT NULL CHECK (version_number > 0), + source_commit_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + target_proof_json TEXT NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + release_content_bytes BYTEA NOT NULL CHECK (octet_length(release_content_bytes) > 0), + published_release_bundle_ref VARCHAR(1024) NOT NULL CHECK (char_length(published_release_bundle_ref) > 0), + published_release_bundle_digest VARCHAR(71) NOT NULL CHECK (published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$'), + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE, + manifest_hash VARCHAR(71) NOT NULL CHECK (manifest_hash ~ '^sha256:[0-9a-f]{64}$'), + publication_version_state_epoch BIGINT NOT NULL CHECK (publication_version_state_epoch > 0), + policy_count INTEGER NOT NULL CHECK (policy_count BETWEEN 1 AND 128), + policy_set_digest VARCHAR(71) NOT NULL CHECK (policy_set_digest ~ '^sha256:[0-9a-f]{64}$'), + sealed BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_realm_policy_capture (canonical_tenant_id, canonical_version_id) +); + +CREATE TABLE game_design_published_realm_policy ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + ordinal INTEGER NOT NULL CHECK (ordinal BETWEEN 0 AND 127), + realm_policy_id UUID NOT NULL UNIQUE, + source_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + logical_revision_id VARCHAR(128) NOT NULL CHECK (char_length(logical_revision_id) BETWEEN 1 AND 128), + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + policy_json TEXT NOT NULL CHECK (char_length(policy_json) BETWEEN 2 AND 4096), + policy_digest VARCHAR(71) NOT NULL CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$'), + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, realm_policy_id), + UNIQUE (canonical_tenant_id, canonical_version_id, ordinal), + UNIQUE (canonical_tenant_id, canonical_version_id, world_slug, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, source_revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_published_realm_policy_set (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_published_realm_policy_set() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; owner_game game%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; + capture game_design_realm_policy_capture%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + release published_release_bundle%ROWTYPE; + row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published realm policy set is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.sealed IS DISTINCT FROM FALSE OR NEW.sealed IS DISTINCT FROM TRUE + OR (to_jsonb(NEW) - 'sealed') IS DISTINCT FROM (to_jsonb(OLD) - 'sealed') THEN + RAISE EXCEPTION 'published realm policy set may only be sealed once' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF row_count <> NEW.policy_count + OR row_count <> jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') + OR realm_count <> row_count OR production_count <> 1 + OR NEW.policy_set_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy set is incomplete or has invalid cardinality' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.sealed IS DISTINCT FROM FALSE + OR jsonb_typeof(NEW.target_proof_json::JSONB) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + SELECT count(*) INTO target_proof_key_count + FROM jsonb_object_keys(NEW.target_proof_json::JSONB); + IF target_proof_key_count <> 7 + OR (NEW.target_proof_json::JSONB - ARRAY['canonicalTenantId', 'canonicalVersionId', 'gameDesignVersionRowId', + 'gameDesignVersionTenantKey', 'sourceGameRowId', 'sourceGameTenantKey', 'sourceProvenanceKind']) + IS DISTINCT FROM '{}'::JSONB + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalVersionId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceProvenanceKind') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO owner_version FROM version v JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id::TEXT = NEW.target_proof_json::JSONB->>'sourceGameRowId' + AND v.identity_source_game_tenant_key = NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + AND v.identity_source_provenance_kind = NEW.target_proof_json::JSONB->>'sourceProvenanceKind'; + IF NOT FOUND OR owner_version.id IS DISTINCT FROM NEW.game_design_version_row_id + OR owner_version.version_state IS DISTINCT FROM 'PUBLISHED' + OR owner_version.version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR owner_version.version_number IS DISTINCT FROM NEW.version_number + OR owner_version.is_script_only IS DISTINCT FROM FALSE + OR owner_version.script_patch_version IS NOT NULL + OR owner_version.base_version_id IS NOT NULL + OR NEW.target_proof_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR NEW.target_proof_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.target_proof_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.target_proof_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.target_proof_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'published realm policy set differs from exact full Version owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT g.* INTO STRICT owner_game FROM game g WHERE g.id = owner_version.identity_source_game_row_id; + IF owner_game.id::TEXT IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameRowId' + OR owner_game.tenant_id IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + OR owner_game.tenant_identity_provenance_kind IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceProvenanceKind' + OR owner_game.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id THEN + RAISE EXCEPTION 'published realm policy set source provenance changed' USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set operation is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO capture FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set source capture is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT * INTO release FROM published_release_bundle + WHERE tenant_id = owner_version.tenant_id AND version_id = owner_version.id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set release bundle is unavailable' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome IS DISTINCT FROM 'PUBLISHED' + OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.terminal_evidence_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR operation.release_content_bytes IS DISTINCT FROM NEW.release_content_bytes + OR operation.published_release_bundle_digest IS DISTINCT FROM NEW.published_release_bundle_digest + OR operation.publication_version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR operation.tenant_id IS DISTINCT FROM owner_version.tenant_id + OR operation.version_id IS DISTINCT FROM owner_version.id + OR operation.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR capture.commit_id IS DISTINCT FROM NEW.source_commit_id + OR snapshot.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR publication_release_content(release) IS DISTINCT FROM NEW.release_content_bytes + OR 'sha256:' || encode(sha256(publication_release_content(release)), 'hex') + IS DISTINCT FROM NEW.published_release_bundle_digest + OR release.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR release.version_number IS DISTINCT FROM NEW.version_number + OR release.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR release.manifest_hash IS DISTINCT FROM NEW.manifest_hash + OR to_jsonb(release)::TEXT IS DISTINCT FROM operation.release_row_json + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.visible_commit_id = NEW.source_commit_id AND s.source_epoch = NEW.source_epoch) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.commit_id = NEW.source_commit_id) + OR jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') <> NEW.policy_count THEN + RAISE EXCEPTION 'published realm policy set is not bound to exact sealed operation, capture, source, and release' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy_set FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_set(); + +CREATE FUNCTION guard_published_realm_policy_row() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + matching JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'published realm policy rows are immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND OR set_row.sealed THEN + RAISE EXCEPTION 'published realm policy row requires its open atomic set' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = set_row.source_commit_id; + SELECT p INTO matching FROM jsonb_array_elements(snapshot.snapshot_json::JSONB->'policies') + WITH ORDINALITY AS entries(p, source_ordinal) + WHERE source_ordinal = NEW.ordinal + 1 + AND p->>'commitId' = NEW.source_commit_id::TEXT + AND p->>'revisionId' = NEW.source_revision_id::TEXT + AND p->>'logicalRevisionId' = NEW.logical_revision_id + AND p->'policy' = NEW.policy_json::JSONB; + IF matching IS NULL + OR NEW.world_slug IS DISTINCT FROM matching->'policy'->>'worldSlug' + OR NEW.realm_slug IS DISTINCT FROM matching->'policy'->>'realmSlug' + OR NEW.visible IS DISTINCT FROM (matching->'policy'->>'visible')::BOOLEAN + OR NEW.public_production IS DISTINCT FROM (matching->'policy'->>'publicProduction')::BOOLEAN + OR jsonb_typeof(NEW.policy_json::JSONB) IS DISTINCT FROM 'object' + OR NEW.policy_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy row differs from exact captured source revision' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_row_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_row(); + +CREATE FUNCTION verify_published_realm_policy_set_commit() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; row_count BIGINT; + realm_count BIGINT; production_count BIGINT; +BEGIN + SELECT * INTO STRICT set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT set_row.sealed OR row_count <> set_row.policy_count OR realm_count <> row_count + OR production_count <> 1 OR row_count NOT BETWEEN 1 AND 128 THEN + RAISE EXCEPTION 'published realm policy set did not commit as one complete canonical set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER published_realm_policy_set_commit_guard + AFTER INSERT OR UPDATE ON game_design_published_realm_policy_set + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_published_realm_policy_set_commit(); + +CREATE FUNCTION deny_published_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'published realm policy evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy_set FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +CREATE TRIGGER published_realm_policy_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql new file mode 100644 index 0000000000..aee294ac4a --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql @@ -0,0 +1,480 @@ +CREATE TABLE game_design_command_source_baseline ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + baseline_kind VARCHAR(32) NOT NULL, + receipt_id UUID NOT NULL, + creation_transaction_id TEXT NOT NULL, + target_proof_json TEXT NOT NULL, + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + UNIQUE (receipt_id), + UNIQUE (game_design_version_row_id), + FOREIGN KEY (game_design_version_row_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + FOREIGN KEY (game_design_version_row_id) + REFERENCES game_design_realm_policy_version_insert (version_id) ON DELETE RESTRICT, + CHECK (baseline_kind = 'NEW_DRAFT_EMPTY'), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_command_source_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence + (canonical_tenant_id, canonical_version_id, request_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + operations_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit + (canonical_tenant_id, canonical_version_id, request_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_operation ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), + revision_id UUID NOT NULL, + operation_kind VARCHAR(16) NOT NULL CHECK (operation_kind IN ('UPSERT', 'DELETE')), + command_id TEXT NOT NULL CHECK (char_length(command_id) > 0), + command_key TEXT NOT NULL CHECK (char_length(command_key) > 0), + definition_json TEXT, + operation_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + UNIQUE (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + CHECK (revision_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK ((operation_kind = 'UPSERT' AND definition_json IS NOT NULL) + OR (operation_kind = 'DELETE' AND definition_json IS NULL)) +); + +CREATE TABLE game_design_command_source_head ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + applied_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_command_source_baseline (canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE + REFERENCES game_design_publication_operation (publish_workflow_id) ON DELETE RESTRICT, + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE game_design_command_source_application + ADD CONSTRAINT command_source_application_json_shape CHECK ( + jsonb_typeof(snapshot_json::JSONB) = 'object' + AND jsonb_typeof(operations_json::JSONB) = 'array' + AND jsonb_array_length(operations_json::JSONB) > 0); +ALTER TABLE game_design_command_source_operation + ADD CONSTRAINT command_source_operation_json_shape CHECK ( + jsonb_typeof(operation_json::JSONB) = 'object'); + +CREATE FUNCTION guard_command_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; binding game_design_draft_commit%ROWTYPE; + witness game_design_realm_policy_version_insert%ROWTYPE; source_head game_design_command_source_head%ROWTYPE; + owner_result game_design_draft_commit_owner_result%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; snapshot game_design_command_source_snapshot%ROWTYPE; + expected BYTEA; payload BYTEA; receipt JSONB; proof JSONB; stored_operation JSONB; revision_payload JSONB; + revision_payload_text TEXT; declared_command_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'command source evidence cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO STRICT owner_version FROM version v JOIN game g + ON g.id = v.identity_source_game_row_id AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF v; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'command source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_baseline' THEN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source baseline is immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert + WHERE version_id = NEW.game_design_version_row_id; + proof := NEW.target_proof_json::JSONB; + receipt := convert_from(NEW.receipt_bytes, 'UTF8')::JSONB; + IF NEW.baseline_kind <> 'NEW_DRAFT_EMPTY' OR owner_version.id <> NEW.game_design_version_row_id + OR owner_version.version_state_epoch <> 1 OR witness.creation_transaction_id <> NEW.creation_transaction_id + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR proof->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR proof->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR proof->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR proof->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR proof->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR proof->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR proof->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind + OR jsonb_typeof(proof) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(proof)) <> 7 + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 4 + OR receipt->>'schema' IS DISTINCT FROM 'game-design-command-source-new-draft-genesis/v1' + OR receipt->'targetProof' IS DISTINCT FROM proof + OR receipt->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR receipt->>'creationTransactionId' IS DISTINCT FROM NEW.creation_transaction_id THEN + RAISE EXCEPTION 'command source baseline lacks exact fresh Version insertion evidence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_head' THEN + IF TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL OR NEW.applied_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_baseline b + WHERE b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.canonical_version_id = NEW.canonical_version_id + AND b.receipt_digest = NEW.baseline_digest) THEN + RAISE EXCEPTION 'command source head must start at its exact empty Draft baseline' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.baseline_digest IS DISTINCT FROM OLD.baseline_digest + OR EXISTS (SELECT 1 FROM game_design_command_source_capture c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id AND c.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'command source head is frozen or its identity changed' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR NEW.applied_commit_id IS NULL OR NEW.applied_commit_id IS NOT DISTINCT FROM OLD.applied_commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.applied_commit_id + AND a.expected_epoch = OLD.source_epoch) THEN + RAISE EXCEPTION 'command source staged epoch must advance by its exact application' USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN + RAISE EXCEPTION 'command source applied pointer changes only with an epoch advance' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.visible_commit_id; + IF snapshot.inherited_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR snapshot.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = snapshot.request_id AND f.commit_id = snapshot.commit_id + AND f.input_digest = snapshot.input_digest AND c.workflow_state = 'SYNCHRONIZED' + AND v.request_id = f.request_id AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest) THEN + RAISE EXCEPTION 'command source visibility must advance to the exact synchronized coordinator fence' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; + END IF; + + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source history is immutable' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' + OR TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT binding FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF binding.binding_json IS DISTINCT FROM NEW.binding_json OR binding.input_digest IS DISTINCT FROM NEW.input_digest THEN + RAISE EXCEPTION 'command source differs from exact Draft binding' USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF source_head.source_epoch IS DISTINCT FROM NEW.expected_epoch + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) + OR NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR jsonb_typeof(NEW.operations_json::JSONB) IS DISTINCT FROM 'array' + OR jsonb_array_length(NEW.operations_json::JSONB) = 0 THEN + RAISE EXCEPTION 'command application must bind exact predecessor, baseline, epoch, and complete set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_operation' THEN + SELECT * INTO STRICT binding FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id AND c.canonical_version_id = NEW.canonical_version_id + AND c.commit_id = NEW.commit_id AND EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = c.canonical_tenant_id AND a.canonical_version_id = c.canonical_version_id + AND a.commit_id = c.commit_id); + SELECT rev->>'payload' INTO STRICT revision_payload_text FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') rev + WHERE rev->>'revisionOrder' = NEW.revision_order::TEXT AND rev->>'revisionId' = NEW.revision_id::TEXT + AND rev->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + revision_payload := revision_payload_text::JSONB; + stored_operation := NEW.operation_json::JSONB; + IF revision_payload->>'revisionKind' IS DISTINCT FROM 'COMMAND_DEFINITION' + OR revision_payload->>'schemaVersion' IS DISTINCT FROM '1' + OR (SELECT count(*) FROM jsonb_object_keys(revision_payload)) <> 4 + OR revision_payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR (SELECT count(*) FROM jsonb_object_keys(stored_operation)) + <> (CASE WHEN NEW.operation_kind = 'UPSERT' THEN 6 ELSE 5 END) + OR stored_operation->>'revisionOrder' IS DISTINCT FROM NEW.revision_order::TEXT + OR stored_operation->>'revisionId' IS DISTINCT FROM NEW.revision_id::TEXT + OR stored_operation->>'commitId' IS DISTINCT FROM NEW.commit_id::TEXT + OR stored_operation->>'operation' IS DISTINCT FROM NEW.operation_kind + OR stored_operation->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command operation must retain its exact authored revision identity' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.operation_kind = 'UPSERT' THEN + IF revision_payload->>'definitionJson' IS DISTINCT FROM NEW.definition_json + OR revision_payload->>'definitionJson' IS DISTINCT FROM stored_operation->>'definitionJson' + OR NEW.definition_json::JSONB->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command upsert definition differs from digest-bound authored payload' USING ERRCODE = 'check_violation'; + END IF; + ELSIF revision_payload->>'commandId' IS DISTINCT FROM NEW.command_id + OR revision_payload ? 'definitionJson' OR stored_operation ? 'definitionJson' THEN + RAISE EXCEPTION 'command delete must retain explicit identity without inferred absence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + SELECT count(*) INTO declared_command_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF (declared_command_count > 0) IS DISTINCT FROM (EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id)) THEN + RAISE EXCEPTION 'command-bearing synchronized commit requires its exact staged command application' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR source_head.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id + AND f.input_digest = NEW.input_digest AND v.request_id = f.request_id + AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest AND c.workflow_state = 'SYNCHRONIZED') THEN + RAISE EXCEPTION 'command snapshot must retain complete source at exact synchronized fence' USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) THEN + RAISE EXCEPTION 'command snapshot differs from exact staged application' USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id) + AND coalesce(NEW.snapshot_json::JSONB->'definitions', '[]'::JSONB) + IS DISTINCT FROM coalesce((SELECT s.snapshot_json::JSONB->'definitions' + FROM game_design_command_source_snapshot s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.commit_id = NEW.inherited_commit_id), '[]'::JSONB) THEN + RAISE EXCEPTION 'disjoint synchronized commit must inherit exact complete command set' USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'command source is frozen by publication selection' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR source_head.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR source_head.source_epoch IS DISTINCT FROM snapshot.source_epoch + OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'command capture must bind actual pending operation and exact selected synchronized source' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'command capture bytes differ from immutable source and operation' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_command_source_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; owner_result game_design_draft_commit_owner_result%ROWTYPE; + source_head game_design_command_source_head%ROWTYPE; + expected BYTEA; payload BYTEA; operation_count BIGINT; declared_count BIGINT; mutation_count BIGINT; +BEGIN + SELECT * INTO STRICT binding FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT owner_result FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO operation_count FROM game_design_command_source_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT jsonb_array_length(NEW.operations_json::JSONB) INTO declared_count; + SELECT count(*) INTO mutation_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF owner_result.status <> 'APPLIED' OR owner_result.result_commit_id <> NEW.commit_id + OR owner_result.result_binding_digest <> binding.input_digest OR declared_count <> operation_count + OR mutation_count <> operation_count + OR source_head.source_epoch IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR source_head.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR owner_result.applied_units_json IS NULL + OR NOT owner_result.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'COMMAND_DEFINITION_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'COMMAND_DEFINITION_SET', 'scopeId', 'effective', + 'expectedEpoch', NEW.expected_epoch, + 'resultingEpoch', (NEW.expected_epoch::NUMERIC + 1)::TEXT)) THEN + RAISE EXCEPTION 'command application requires exact combined control-plane APPLIED owner outcome' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(coalesce(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.operations_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.result_bytes THEN + RAISE EXCEPTION 'command application result bytes do not encode exact mutation and effective snapshot' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER command_source_baseline_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_baseline + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_application + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_operation + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_head + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE CONSTRAINT TRIGGER command_source_application_commit_guard AFTER INSERT ON game_design_command_source_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_command_source_application_commit(); + +CREATE FUNCTION deny_command_source_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'command source evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER command_source_baseline_no_truncate BEFORE TRUNCATE ON game_design_command_source_baseline + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_snapshot_no_truncate BEFORE TRUNCATE ON game_design_command_source_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_application_no_truncate BEFORE TRUNCATE ON game_design_command_source_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_operation_no_truncate BEFORE TRUNCATE ON game_design_command_source_operation + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_head_no_truncate BEFORE TRUNCATE ON game_design_command_source_head + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_capture_no_truncate BEFORE TRUNCATE ON game_design_command_source_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V55__immutable_reviewed_draft_base.sql b/services/game-design-service/src/main/resources/db/migration/V55__immutable_reviewed_draft_base.sql new file mode 100644 index 0000000000..e33d79335d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V55__immutable_reviewed_draft_base.sql @@ -0,0 +1,171 @@ +-- New reviewed claims only. Existing opaque bindings and retained history are not backfilled. +CREATE TABLE game_design_reviewed_draft_base ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + base_kind VARCHAR(32) NOT NULL CHECK (base_kind IN ('GENESIS', 'AUTHORED_COMMIT')), + base_identity UUID NOT NULL CHECK (base_identity <> '00000000-0000-0000-0000-000000000000'), + base_reference VARCHAR(44) NOT NULL, + evidence_schema VARCHAR(64) NOT NULL CHECK (evidence_schema = 'game-design-reviewed-draft-base/v1'), + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) > 0), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, request_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id) + ON DELETE RESTRICT, + CHECK (base_reference = CASE WHEN base_kind = 'GENESIS' THEN 'genesis:' ELSE '' END || base_identity::TEXT) +); + +-- [jooq ignore start] +CREATE FUNCTION game_design_reviewed_base_frame(value BYTEA) RETURNS BYTEA +LANGUAGE SQL IMMUTABLE STRICT AS $$ SELECT int4send(octet_length(value)) || value $$; +CREATE FUNCTION game_design_reviewed_base_frame(value TEXT) RETURNS BYTEA +LANGUAGE SQL IMMUTABLE STRICT AS $$ SELECT game_design_reviewed_base_frame(convert_to(value, 'UTF8')) $$; + +CREATE FUNCTION protect_game_design_reviewed_base() RETURNS trigger AS $$ +DECLARE + claim game_design_draft_commit%ROWTYPE; + owner_version version%ROWTYPE; + policy_genesis game_design_realm_policy_genesis%ROWTYPE; + command_genesis game_design_command_source_baseline%ROWTYPE; + witness game_design_realm_policy_version_insert%ROWTYPE; + base game_design_draft_commit%ROWTYPE; + policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + command_snapshot game_design_command_source_snapshot%ROWTYPE; + fence game_design_draft_commit_visibility_fence%ROWTYPE; + owner_result game_design_draft_commit_owner_result%ROWTYPE; + owner_name TEXT; + outcome JSONB; + epoch JSONB; + source_bytes BYTEA; + expected_bytes BYTEA; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Reviewed Draft base evidence is immutable'; + END IF; + SELECT * INTO STRICT claim FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT owner_version FROM version WHERE id = claim.game_design_version_row_id FOR UPDATE; + IF claim.binding_json IS DISTINCT FROM NEW.binding_json OR claim.input_digest IS DISTINCT FROM NEW.input_digest + OR claim.base_commit_id IS DISTINCT FROM NEW.base_reference OR claim.workflow_state <> 'QUEUED' + OR EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.request_id = NEW.request_id AND r.status <> 'NOT_ATTEMPTED') + OR EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id + AND s.request_id = NEW.request_id) + OR owner_version.version_state <> 'DRAFT' + OR owner_version.is_script_only OR owner_version.base_version_id IS NOT NULL + OR owner_version.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'Reviewed base requires exact new full Draft binding'; + END IF; + IF NEW.base_kind = 'GENESIS' THEN + SELECT * INTO STRICT policy_genesis FROM game_design_realm_policy_genesis + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND receipt_id = NEW.base_identity AND version_id = claim.game_design_version_row_id; + SELECT * INTO STRICT command_genesis FROM game_design_command_source_baseline + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND receipt_id = NEW.base_identity AND game_design_version_row_id = claim.game_design_version_row_id; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert + WHERE version_id = claim.game_design_version_row_id; + IF policy_genesis.creation_transaction_id IS DISTINCT FROM witness.creation_transaction_id + OR command_genesis.creation_transaction_id IS DISTINCT FROM witness.creation_transaction_id + OR command_genesis.baseline_kind <> 'NEW_DRAFT_EMPTY' THEN + RAISE EXCEPTION 'Reviewed genesis must retain original shared receipt and insertion witness'; + END IF; + source_bytes := game_design_reviewed_base_frame('shared-policy-command-genesis/v1'::TEXT) + || game_design_reviewed_base_frame(witness.creation_transaction_id) + || game_design_reviewed_base_frame(convert_to(policy_genesis.receipt_json, 'UTF8')) + || game_design_reviewed_base_frame(command_genesis.receipt_bytes); + ELSE + SELECT * INTO STRICT base FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity; + SELECT * INTO STRICT fence FROM game_design_draft_commit_visibility_fence + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + SELECT * INTO STRICT policy_snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + SELECT * INTO STRICT command_snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.base_identity AND request_id = base.request_id; + IF base.workflow_state <> 'SYNCHRONIZED' OR fence.input_digest IS DISTINCT FROM base.input_digest + OR command_snapshot.binding_json IS DISTINCT FROM base.binding_json + OR command_snapshot.input_digest IS DISTINCT FROM base.input_digest + OR policy_snapshot.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM base.binding_json + OR policy_snapshot.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM base.input_digest + OR (base.game_design_version_row_id, base.game_design_version_tenant_key, base.source_game_row_id, + base.source_game_tenant_key, base.source_provenance_kind) IS DISTINCT FROM + (claim.game_design_version_row_id, claim.game_design_version_tenant_key, claim.source_game_row_id, + claim.source_game_tenant_key, claim.source_provenance_kind) + OR jsonb_array_length(fence.result_vector_json::JSONB) <> + jsonb_array_length(base.binding_json::JSONB->'requiredOwners') THEN + RAISE EXCEPTION 'Reviewed authored base requires complete exact retained synchronized source'; + END IF; + source_bytes := game_design_reviewed_base_frame('retained-authored-policy-command-base/v1'::TEXT) + || game_design_reviewed_base_frame(convert_to(base.binding_json, 'UTF8')) + || game_design_reviewed_base_frame(convert_to(policy_snapshot.snapshot_json, 'UTF8')) + || game_design_reviewed_base_frame(convert_to(command_snapshot.snapshot_json, 'UTF8')) + || game_design_reviewed_base_frame(jsonb_array_length(base.binding_json::JSONB->'requiredOwners')::TEXT); + FOR owner_name IN SELECT jsonb_array_elements_text(base.binding_json::JSONB->'requiredOwners') LOOP + SELECT * INTO STRICT owner_result FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = base.request_id AND owner = owner_name; + SELECT item INTO STRICT outcome FROM jsonb_array_elements(fence.result_vector_json::JSONB) item + WHERE item->>'owner' = owner_name; + IF owner_result.status <> 'APPLIED' OR owner_result.result_commit_id IS DISTINCT FROM base.commit_id + OR owner_result.result_binding_digest IS DISTINCT FROM base.input_digest + OR outcome IS DISTINCT FROM jsonb_build_object('owner', owner_name, 'status', owner_result.status, + 'commitId', owner_result.result_commit_id::TEXT, 'bindingDigest', owner_result.result_binding_digest, + 'resultIdentity', owner_result.result_identity, + 'resultBytesBase64', replace(encode(owner_result.result_bytes, 'base64'), E'\n', ''), + 'appliedEpochs', owner_result.applied_units_json::JSONB) THEN + RAISE EXCEPTION 'Reviewed authored owner vector differs from retained exact outcome'; + END IF; + source_bytes := source_bytes || game_design_reviewed_base_frame(owner_name) + || game_design_reviewed_base_frame(owner_result.status::TEXT) + || game_design_reviewed_base_frame(base.commit_id::TEXT) + || game_design_reviewed_base_frame(base.input_digest::TEXT) + || game_design_reviewed_base_frame(owner_result.result_identity::TEXT) + || game_design_reviewed_base_frame(owner_result.result_bytes) + || game_design_reviewed_base_frame(jsonb_array_length(outcome->'appliedEpochs')::TEXT); + FOR epoch IN SELECT jsonb_array_elements(outcome->'appliedEpochs') LOOP + source_bytes := source_bytes || game_design_reviewed_base_frame(epoch->>'aggregateType') + || game_design_reviewed_base_frame(epoch->>'aggregateId') + || game_design_reviewed_base_frame(epoch->>'scopeType') + || game_design_reviewed_base_frame(epoch->>'scopeId') + || game_design_reviewed_base_frame(epoch->>'expectedEpoch') + || game_design_reviewed_base_frame(epoch->>'resultingEpoch'); + END LOOP; + END LOOP; + END IF; + expected_bytes := game_design_reviewed_base_frame(NEW.evidence_schema::TEXT) + || game_design_reviewed_base_frame('game-design-draft-base-reference/v1'::TEXT) + || game_design_reviewed_base_frame(NEW.base_kind::TEXT) + || game_design_reviewed_base_frame(NEW.base_reference::TEXT) + || game_design_reviewed_base_frame(NEW.canonical_tenant_id::TEXT) + || game_design_reviewed_base_frame(NEW.canonical_version_id::TEXT) + || game_design_reviewed_base_frame(claim.game_design_version_row_id::TEXT) + || game_design_reviewed_base_frame(claim.game_design_version_tenant_key::TEXT) + || game_design_reviewed_base_frame(claim.source_game_row_id::TEXT) + || game_design_reviewed_base_frame(claim.source_game_tenant_key::TEXT) + || game_design_reviewed_base_frame(claim.source_provenance_kind::TEXT) + || game_design_reviewed_base_frame(source_bytes); + IF NEW.evidence_bytes IS DISTINCT FROM expected_bytes + OR NEW.evidence_digest IS DISTINCT FROM 'sha256:' || encode(sha256(expected_bytes), 'hex') THEN + RAISE EXCEPTION 'Reviewed base bytes or digest differ from exact owner provenance'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_design_reviewed_base_protected + BEFORE INSERT OR UPDATE OR DELETE ON game_design_reviewed_draft_base + FOR EACH ROW EXECUTE FUNCTION protect_game_design_reviewed_base(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java new file mode 100644 index 0000000000..7dbc0ae8fe --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -0,0 +1,307 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.math.BigInteger; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; + +/** + * ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. + */ +public final class IsolatedPublicationOwnerSetup { + private IsolatedPublicationOwnerSetup() {} + + /** Fixture-only visibility advance; supplied owner authority remains explicitly isolated. */ + public static void advanceIsolatedVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + + /** + * Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. + */ + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED owner transaction proof"); + } + + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, false); + } + + /** Actual source inheritance precedes selection; only the remote owner inputs are isolated. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED remote owner transaction proof", true); + } + + /** Actual source inheritance precedes selection; this does not freeze selected source. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, true); + } + + /** + * Finalizer-only fixture: author a complete minimal policy, select a later World-only commit, and + * freeze both exact selected source captures in the caller-owned owner transaction. + */ + public static GameDesignPublicationOperation retainFrozenSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target); + GameDesignPublicationOperation operation = + retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit); + new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation); + return operation; + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources) + throws Exception { + return retain(dsl, target, draftEpoch, notes, captureSources, null); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + String sourceBaseReference) + throws Exception { + var sources = new GameDesignSourceRepository(dsl); + var reviewed = new GameDesignReviewedBaseRepository(dsl); + var evidence = + captureSources + ? reviewed.resolve( + target, + DraftBaseReference.parse( + sourceBaseReference == null + ? "genesis:" + + sources.readGenesis(target).orElseThrow().policy().receiptId() + : sourceBaseReference)) + : null; + var seed = + captureSources + ? IsolatedPublicationOperationFixtures.fresh( + target, evidence.reference().canonicalValue()) + : IsolatedPublicationOperationFixtures.fresh(target); + var draft = seed.account().input().selection().selectedCommit(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + // The original Draft Account/World result is stipulated upstream fixture evidence, not a new + // GD Draft-authorization operation or live Account authority issued by this helper. + if (captureSources) { + sources.claimReviewed(draft, evidence); + } else { + coordinator.claim(draft); + } + coordinator.claimApplicationSlot(draft); + var epochs = + draft.affectedUnits().stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + draft.commitId(), + draft.digest(), + "ISOLATED-world-applied", + seed.world().appliedResultBytes(), + epochs); + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(draft, outcome); + var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome)); + if (captureSources) { + coordinator.advanceSourceVisibilityFence(draft, proof); + } else { + coordinator.advanceVisibilityFence(draft, proof); + } + coordinator.releaseApplicationSlot(draft); + var selection = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), + Long.toString(draftEpoch), + notes, + draft.requestId(), + draft.commitId(), + draft.digest())) + .selection(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + seed.world()); + var attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + var versionRow = + dsl.fetchOne( + "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); + if (versionRow == null) { + throw new IllegalStateException("Selected authored Version row is absent"); + } + attempt.setVersionNumber(versionRow.get(0, Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(dsl).save(attempt); + GameDesignPublicationOperationRepository operations = + new GameDesignPublicationOperationRepository(dsl); + operations.reserve(operation); + return operation; + } + + private static String retainPublicProductionPolicy( + DSLContext dsl, DraftCommitBinding.TargetProof target) { + var sources = new GameDesignSourceRepository(dsl); + var genesis = sources.readGenesis(target).orElseThrow(); + String baseReference = "genesis:" + genesis.policy().receiptId(); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + baseReference, + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"," + + "\"logicalRevisionId\":\"isolated-finalizer-main\"," + + "\"policy\":{\"schemaVersion\":1,\"worldSlug\":\"world\"," + + "\"worldDisplayName\":\"World\",\"realmSlug\":\"main\"," + + "\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var reviewed = new GameDesignReviewedBaseRepository(dsl); + sources.claimReviewed( + binding, reviewed.resolve(target, DraftBaseReference.parse(baseReference))); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + coordinator.releaseApplicationSlot(binding); + return binding.commitId().toString(); + } + + /** Storage fixture commit only; does not substitute for actual command finalization proof. */ + public static PublishedReleaseBundle commitStorage( + DSLContext dsl, + VersionRepository versions, + GameDesignPublicationOperation operation, + Supplier releaseWrite) { + var attempts = new PublishAttemptRepository(dsl); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + attempts.requirePublishedOperation(attempt); + return releaseWrite.get(); + } + attempts.requirePublicationPending(attempt); + var version = + versions + .findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()) + .orElseThrow(); + var snapshot = + new VersionAssetPublicationRepository(dsl) + .freezeOrReadSnapshot(operation.tenantKey(), version.getVersionNumber()); + PublishedReleaseBundle bundle = releaseWrite.get(); + if (snapshot.versionId() != operation.versionId() + || !snapshot.items().isEmpty() + || bundle.getManifestSchemaVersion() == null + || bundle.getManifestSchemaVersion() != 1 + || !"[]".equals(bundle.getArtifactDigestsJson()) + || !"[]".equals(bundle.getRequiredManifestAssetKeysJson()) + || bundle.getManifestHash() == null + || !bundle.getManifestHash().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + "Isolated publication fixture requires the exact empty asset candidate for its Version"); + } + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); + versions.save(version); + var artifact = new VersionAssetArtifact(); + artifact.setTenantId(operation.tenantKey()); + artifact.setVersionId(operation.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(operation.workflowId()); + artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); + artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); + artifact.setExportedManifestAssetKeysJson(bundle.getRequiredManifestAssetKeysJson()); + String manifestDigest = bundle.getManifestHash(); + artifact.setPublishedObjectProofsJson( + "[{\"immutableObjectKey\":\"manifests/sha256/" + + manifestDigest.substring("sha256:".length()) + + "\",\"contentDigest\":\"" + + manifestDigest + + "\"}]"); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + new VersionAssetArtifactRepository(dsl).save(artifact); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + attempts.sealPublication(attempt, true); + return bundle; + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java new file mode 100644 index 0000000000..9457f43972 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import tools.jackson.databind.ObjectMapper; + +/** + * ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. + */ +public final class IsolatedPublicationOperationFixtures { + private IsolatedPublicationOperationFixtures() {} + + /** + * A new fixture operation and freeze, never a reinterpretation of retained publication history. + */ + public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) + throws Exception { + var seed = PublishedWorldSelectorFixtures.evidence(target); + return fresh(target, seed); + } + + public static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, String baseReference) throws Exception { + return fresh(target, PublishedWorldSelectorFixtures.evidence(target, baseReference)); + } + + private static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence seed) + throws Exception { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), + originalDraftAccount.inputDigest()); + var appliedEpochs = + draft.affectedUnits().stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + String vector = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + List.of( + Map.of( + "owner", + "WORLD_MANAGEMENT", + "status", + "APPLIED", + "commitId", + draft.commitId().toString(), + "bindingDigest", + draft.digest(), + "resultIdentity", + "ISOLATED-world-applied", + "resultBytesBase64", + Base64.getEncoder().encodeToString(seed.appliedResultBytes()), + "appliedEpochs", + appliedEpochs)))), + StandardCharsets.UTF_8); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "ISOLATED-publication-request", + "5", + "ISOLATED owner transaction proof", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + vector, + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + return forSelection(selected, seed); + } + + public static GameDesignPublicationOperation forSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var target = selected.target(); + var intent = selected.intent(); + var draft = selected.selectedCommit(); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalDraftAccount.actorAccountId(), selected), + java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()) + .map( + kind -> + new DraftAuthorizationFenceBinding.SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> + originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> + originalDraftAccount.actorAccountId() + + "/" + + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, + "1", + "1", + null, + null, + ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))) + .toList()); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + seed.request().intakeRequestId(), + UUID.randomUUID(), + intent.publishRequestId(), + selected.digest().substring(7), + Long.parseLong(intent.expectedVersionStateEpoch()), + FiremudWorkflowIds.workflowId( + "publish", + target.canonicalTenantId().toString(), + "publish-request", + intent.publishRequestId()), + draft.commitId().toString(), + seed.request().contentDigest(), + 3, + seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperation(account, world); + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java new file mode 100644 index 0000000000..88161aa7e2 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -0,0 +1,475 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.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.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Stipulated original Account/APPLIED component bytes; no live producer/currentness proof. */ +public final class PublishedWorldSelectorFixtures { + private final TargetProof target; + private final String baseReference; + + private PublishedWorldSelectorFixtures(TargetProof target) { + this(target, "base-1"); + } + + private PublishedWorldSelectorFixtures(TargetProof target, String baseReference) { + this.target = target; + this.baseReference = baseReference; + this.TENANT_ID = target.canonicalTenantId(); + this.VERSION_ID = target.canonicalVersionId(); + } + + public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception { + return new PublishedWorldSelectorFixtures(target).build(); + } + + public static WorldPublishedStartLocationEvidence evidence( + TargetProof target, String baseReference) throws Exception { + net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); + return new PublishedWorldSelectorFixtures(target, baseReference).build(); + } + + /** Adds an explicitly isolated World graph application to the exact supplied Draft binding. */ + public static DraftCommitBinding withIsolatedFreshWorldGraph(DraftCommitBinding binding) + throws Exception { + var fixture = new PublishedWorldSelectorFixtures(binding.target(), binding.baseCommitId()); + var revisions = new ArrayList<>(binding.revisions()); + revisions.addAll(fixture.freshWorldRevisions(binding.commitId(), revisions.size())); + var affectedUnits = new ArrayList<>(binding.affectedUnits()); + affectedUnits.addAll(fixture.freshWorldAffectedUnits()); + return DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + affectedUnits); + } + + /** Stipulates Account and World inputs for this exact binding; this is not producer proof. */ + public static WorldPublishedStartLocationEvidence evidence( + TargetProof target, DraftCommitBinding draft) throws Exception { + if (!target.equals(draft.target())) { + throw new IllegalArgumentException("Isolated World evidence target differs from Draft"); + } + return new PublishedWorldSelectorFixtures(target, draft.baseCommitId()).build(draft); + } + + public static List + participants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return net + .firedevops + .firemud + .common + .gamedesign + .AuthoredWorldReleaseAttestationEvidence + .requiredParticipantOrder() + .stream() + .map( + owner -> + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + owner, + Long.toString(versionId), + null, + evidence.request().appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) + ? evidence.request().contentDigest() + : "c".repeat(64), + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + } + + private WorldPublishedStartLocationEvidence build() throws Exception { + return build(freshGraphBinding()); + } + + private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); + var result = committedReadback(terminal, true); + var applied = JSON.readTree(result.result()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .sorted( + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId) + .thenComparing(AffectedUnit::expectedEpoch)) + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()), + result.fullBinding(), + result.result()); + } + + private final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private final UUID TENANT_ID; + private final UUID VERSION_ID; + private final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.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", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private DraftCommitBinding freshGraphBinding() throws Exception { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + baseReference, + freshWorldRevisions(COMMIT_ID, 0), + freshWorldAffectedUnits()); + } + + private List freshWorldRevisions(UUID commitId, int revisionOffset) + throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return List.of( + new RevisionPayload( + Integer.toString(revisionOffset), + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + Integer.toString(revisionOffset + 1), + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ZONE_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + ZONE_TEMPLATE_ID, + null)), + new RevisionPayload( + Integer.toString(revisionOffset + 2), + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ROOM_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + ROOM_TEMPLATE_ID, + null))); + } + + private List freshWorldAffectedUnits() { + return List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList(); + } + + private String worldRevisionPayload( + UUID commitId, UUID revisionId, String family, UUID templateId, String declaration) + throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", commitId.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + draft.requestId(), + draft.commitId(), + FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.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())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private byte[] historicalGraphBytes(DraftAuthorizationFenceBinding account) { + throw new IllegalArgumentException("This fixture supplies only selector-bearing APPLIED v2"); + } + + private tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(TENANT_ID, VERSION_ID, ROOM_TEMPLATE_ID), + graphDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(receipt.canonicalBytes()); + } + + private byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..92a5b0d530 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -0,0 +1,408 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Real local source writers and coordinator SQL; publication Account and World remain isolated. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); + assertThat(genesis.policy().creationTransactionId()) + .isEqualTo(genesis.command().creationTransactionId()); + assertThat(fixture.tx(() -> fixture.sources().enrollFreshDraft(fixture.target()))) + .isEqualTo(genesis); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + + DraftCommitBinding policy = + binding( + fixture.target(), "genesis:" + genesis.policy().receiptId(), "0", null, "main", true); + var policyResult = apply(fixture, policy); + synchronize(fixture, policy, policyResult); + var policySnapshot = + fixture.sources().readSynchronized(fixture.target(), policy.commitId()).orElseThrow(); + assertThat(policySnapshot.policy().policies()).hasSize(1); + assertThat(policySnapshot.command().definitions()).isEmpty(); + + DraftCommitBinding command = + binding(fixture.target(), policy.commitId().toString(), null, "0", null, false); + var commandResult = apply(fixture, command); + synchronize(fixture, command, commandResult); + var commandSnapshot = + fixture.sources().readSynchronized(fixture.target(), command.commitId()).orElseThrow(); + assertThat(commandSnapshot.policy().policies()) + .containsExactlyElementsOf(policySnapshot.policy().policies()); + assertThat(commandSnapshot.command().definitions()).hasSize(1); + assertThat(commandResult.ownerOutcome().appliedEpochs()) + .containsExactly(commandResult.command().orElseThrow().commandAppliedEpoch()); + + DraftCommitBinding mixed = + binding(fixture.target(), command.commitId().toString(), "1", "1", "main", true); + var mixedResult = apply(fixture, mixed); + assertThat(mixedResult.ownerOutcome().appliedEpochs()).hasSize(2); + assertThat(mixedResult.ownerOutcome().resultBytes()) + .contains(mixedResult.command().orElseThrow().canonicalBytes()); + assertThat(fixture.tx(() -> fixture.sources().apply(policy)).ownerOutcome()) + .isEqualTo(policyResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(command)).ownerOutcome()) + .isEqualTo(commandResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(mixed)).ownerOutcome()) + .isEqualTo(mixedResult.ownerOutcome()); + synchronize(fixture, mixed, mixedResult); + var mixedSnapshot = + fixture.sources().readSynchronized(fixture.target(), mixed.commitId()).orElseThrow(); + assertThat(mixedSnapshot.policy().sourceEpoch()).isEqualTo("2"); + assertThat(mixedSnapshot.command().sourceEpoch()).isEqualTo("2"); + assertThat(mixedSnapshot.command().definitions().getFirst().sourceCommitId()) + .isEqualTo(mixed.commitId()); + assertThat(fixture.tx(() -> fixture.sources().captureSynchronized(mixed))) + .isEqualTo(mixedSnapshot); + assertThat(fixture.tx(() -> fixture.sources().apply(policy)).ownerOutcome()) + .isEqualTo(policyResult.ownerOutcome()); + assertThat(fixture.tx(() -> fixture.sources().apply(command)).ownerOutcome()) + .isEqualTo(commandResult.ownerOutcome()); + } + + @Test + void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { + Fixture fixture = fixture(); + DraftCommitBinding incomplete = + binding( + fixture.target(), + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId(), + "0", + null, + "private", + false); + start(fixture, incomplete); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.sources().apply(incomplete); + status.setRollbackOnly(); + }); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) + .isZero(); + assertThat( + fixture + .coordinator() + .read(fixture.target(), incomplete.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome()) + .isEmpty(); + var result = fixture.tx(() -> fixture.sources().apply(incomplete)); + synchronize(fixture, incomplete, result); + + var unsupported = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + incomplete.commitId().toString(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("unused"))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "1"))); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().apply(unsupported))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete supported Game Design source scopes"); + + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exactly one visible public-production realm"); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + } + + @Test + void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { + Fixture fixture = fixture(); + var authored = + binding( + fixture.target(), + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId(), + "0", + "0", + "main", + true); + synchronize(fixture, authored, apply(fixture, authored)); + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.sources().freeze(operation); + status.setRollbackOnly(); + }); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + var first = fixture.tx(() -> fixture.sources().freeze(operation)); + var retry = fixture.tx(() -> fixture.sources().freeze(operation)); + var read = fixture.sources().readCapture(operation).orElseThrow(); + assertThat(retry.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); + assertThat(retry.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(read.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); + assertThat(read.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(read.command().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(read.policy().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + } + + private static GameDesignSourceRepository.Application apply( + Fixture fixture, DraftCommitBinding binding) { + start(fixture, binding); + return fixture.tx(() -> fixture.sources().apply(binding)); + } + + private static void start(Fixture fixture, DraftCommitBinding binding) { + fixture.tx( + () -> { + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + fixture + .sources() + .claimReviewed( + binding, + reviewed.resolve( + fixture.target(), + net.firedevops.firemud.common.authoring.DraftBaseReference.parse( + binding.baseCommitId()))); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); + } + + private static void synchronize( + Fixture fixture, DraftCommitBinding binding, GameDesignSourceRepository.Application result) { + fixture.tx( + () -> { + fixture + .coordinator() + .advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(result.ownerOutcome()))); + fixture.sources().captureSynchronized(binding); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + } + + private static DraftCommitBinding binding( + TargetProof target, + String base, + String policyEpoch, + String commandEpoch, + String realm, + boolean production) { + var revisions = new java.util.ArrayList(); + var scopes = new java.util.ArrayList(); + if (commandEpoch != null) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload(command("look", realm == null ? "see" : realm)))); + scopes.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + target.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + commandEpoch)); + } + if (policyEpoch != null) { + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-" + + realm + + "\",\"policy\":{\"schemaVersion\":1,\"worldSlug\":\"world\"," + + "\"worldDisplayName\":\"World\",\"realmSlug\":\"" + + realm + + "\"," + + "\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}}"; + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)); + scopes.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + policyEpoch)); + } + return DraftCommitBinding.create( + target, UUID.randomUUID(), UUID.randomUUID(), base, revisions, scopes); + } + + private static String command(String id, String alias) { + return "{\"schemaVersion\":1,\"commandId\":\"" + + id + + "\",\"semanticOwner\":\"WORLD\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"" + + alias + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," + + "\"legacyExtension\":{\"kept\":true}}"; + } + + private static Fixture fixture() { + String schema = "gd_combined_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target("55") + .load() + .migrate(); + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var properties = new PostgresProperties(); + properties.setSchema(schema); + TargetProof target = + write.execute( + status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED composed source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + }); + return new Fixture( + dsl, + write, + target, + new GameDesignSourceRepository(dsl), + new DraftCommitCoordinatorRepository(dsl)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + TargetProof target, + GameDesignSourceRepository sources, + DraftCommitCoordinatorRepository coordinator) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..d1191c3fc9 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -0,0 +1,737 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyApplication; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySnapshot; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceService; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Real GD SQL writes. Initial typed owner baseline, Account currentness and World are ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class RealmPolicySourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { + var fixture = freshFixture(); + var genesis = fixture.reads().readGenesis(fixture.target()).orElseThrow(); + assertThat(fixture.tx(() -> fixture.policies().recordFreshGenesis(fixture.target()))) + .isEqualTo(genesis); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_snapshot"))).isZero(); + var first = policyBinding(fixture.target(), "0", "main", true); + start(fixture, first); + var applied = fixture.tx(() -> fixture.policies().apply(first)); + assertThat(applied.genesis()).isEqualTo(genesis); + assertThat(applied.inheritedCommitId()).isNull(); + assertThat(applied.snapshot().sourceEpoch()).isEqualTo("1"); + assertThat(fixture.tx(() -> fixture.policies().apply(first)).canonicalBytes()) + .containsExactly(applied.canonicalBytes()); + synchronize(fixture, first, applied); + assertThat(fixture.reads().readSnapshot(fixture.target(), first.commitId()).orElseThrow()) + .isEqualTo(applied.snapshot()); + } + + @Test + void incompleteDraftPoliciesCanSynchronizeButCannotBecomePublicationCapture() { + var fixture = freshFixture(); + var first = policyBinding(fixture.target(), "0", "private", false); + start(fixture, first); + var applied = fixture.tx(() -> fixture.policies().apply(first)); + synchronize(fixture, first, applied); + var operation = publication(fixture); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().freeze(operation))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exactly one visible"); + assertThat(fixture.reads().readCapture(operation)).isEmpty(); + } + + @Test + void retainedVersionUpdateIsNotFreshGenesisAndActualCreationRollbackLeavesNoReceipt() { + var fixture = retainedFixture(false); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "UPDATE version SET notes = 'ISOLATED retained update' WHERE id = ?", + fixture.target().gameDesignVersionRowId()); + return fixture.policies().recordFreshGenesis(fixture.target()); + })) + .hasMessageContaining("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); + var rolledBack = new java.util.concurrent.atomic.AtomicReference(); + fixture + .write() + .executeWithoutResult( + status -> { + var properties = new PostgresProperties(); + var version = new Version(); + version.setTenantId(fixture.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + version = new VersionRepository(fixture.dsl()).save(version); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + rolledBack.set(target); + RealmPolicyGenesis receipt = fixture.policies().recordFreshGenesis(target); + assertThat(fixture.policies().recordFreshGenesis(target)).isEqualTo(receipt); + status.setRollbackOnly(); + }); + assertThat(fixture.reads().readGenesis(rolledBack.get())).isEmpty(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT id FROM version WHERE id = ?", + rolledBack.get().gameDesignVersionRowId())) + .isNull(); + } + + @Test + void isolatedSiblingSourceComposesOneOwnerResultAndCommandOnlyFenceInheritsPolicy() { + var fixture = freshFixture(); + var policy = policyBinding(fixture.target(), "0", "main", true); + var commandRevision = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{\"revisionKind\":\"COMMAND_DEFINITION\",\"schemaVersion\":1,\"operation\":\"DELETE\",\"commandId\":\"ISOLATED-command\"}"); + var commandScope = + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "0"); + var mixed = + DraftCommitBinding.create( + policy.target(), + policy.requestId(), + policy.commitId(), + policy.baseCommitId(), + List.of(policy.revisions().getFirst(), commandRevision), + List.of(commandScope, policy.affectedUnits().getFirst())); + start(fixture, mixed); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(mixed))) + .hasMessageContaining("Mixed Game Design commit"); + fixture.tx( + () -> { + var mutation = fixture.policies().applyMutation(mixed); + // ISOLATED assumption: the sibling command owner store has applied/read back these bytes. + // This fixture proves only policy's one-result composition, not the actual command + // writer. + byte[] sibling = + "ISOLATED authenticated command application".getBytes(StandardCharsets.UTF_8); + var epochs = + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "0", + "1"), + mutation.ownerOutcome().appliedEpochs().getFirst()); + fixture.policies().recordCombinedOwnerOutcome(mixed, sibling, epochs); + var outcome = + fixture + .coordinator() + .read(fixture.target(), mixed.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome() + .orElseThrow(); + fixture + .coordinator() + .advanceVisibilityFence( + mixed, + new DraftCommitCoordinatorRepository.CoordinatorProof(mixed, List.of(outcome))); + fixture.policies().captureSynchronized(mixed); + fixture.coordinator().releaseApplicationSlot(mixed); + return null; + }); + var prior = fixture.reads().readSnapshot(fixture.target(), mixed.commitId()).orElseThrow(); + var commandOnly = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + mixed.commitId().toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + commandRevision.payload())), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "1"))); + start(fixture, commandOnly); + fixture.tx( + () -> { + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + commandOnly.commitId(), + commandOnly.digest(), + "ISOLATED-command-only", + "ISOLATED command owner readback".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "1", + "2"))); + fixture.coordinator().recordOwnerOutcome(commandOnly, outcome); + fixture + .coordinator() + .advanceVisibilityFence( + commandOnly, + new DraftCommitCoordinatorRepository.CoordinatorProof( + commandOnly, List.of(outcome))); + var inherited = fixture.policies().captureSynchronized(commandOnly); + assertThat(inherited.sourceEpoch()).isEqualTo(prior.sourceEpoch()); + assertThat(inherited.policies()).containsExactlyElementsOf(prior.policies()); + fixture.coordinator().releaseApplicationSlot(commandOnly); + return null; + }); + } + + @Test + void absentBaselineDeniesAndApplicationReplayAndMismatchBindActualCoordinatorResult() { + var fixture = retainedFixture(false); + var binding = policyBinding(fixture.target(), "0", "main", true); + start(fixture, binding); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(binding))) + .hasMessageContaining("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + var real = retainedFixture(true); + var mutation = policyBinding(real.target(), "1", "private", false); + start(real, mutation); + var result = real.tx(() -> real.policies().apply(mutation)); + assertThat(real.tx(() -> real.policies().apply(mutation)).canonicalBytes()) + .containsExactly(result.canonicalBytes()); + var changed = + DraftCommitBinding.create( + mutation.target(), + mutation.requestId(), + mutation.commitId(), + mutation.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + mutation.revisions().getFirst().revisionId(), + Owner.GAME_DESIGN_CONTROL_PLANE, + mutation.revisions().getFirst().payload().replace("private", "changed"))), + mutation.affectedUnits()); + assertThatThrownBy(() -> real.tx(() -> real.policies().apply(changed))) + .hasMessageContaining("POLICY_COMMIT_BINDING_CONFLICT"); + assertThat( + real.coordinator() + .read(real.target(), mutation.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome()) + .contains(result.ownerOutcome()); + } + + @Test + void rollbackAndPartialWritesPreserveLastVisibleSourceThenDisjointCommitInheritsExactProvenance() + throws Exception { + var fixture = retainedFixture(true); + var mutation = policyBinding(fixture.target(), "1", "private", false); + start(fixture, mutation); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.policies().apply(mutation); + status.setRollbackOnly(); + }); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) + .isZero(); + var result = fixture.tx(() -> fixture.policies().apply(mutation)); + assertThat( + fixture + .reads() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow() + .policies()) + .hasSize(1); + assertThat(fixture.reads().readSnapshot(fixture.target(), mutation.commitId())).isEmpty(); + synchronize(fixture, mutation, result); + var operation = publication(fixture); + var inherited = + fixture + .reads() + .readSnapshot( + fixture.target(), + operation.account().input().selection().selectedCommit().commitId()) + .orElseThrow(); + assertThat(inherited.policies()).containsExactlyElementsOf(result.snapshot().policies()); + var capture = fixture.tx(() -> fixture.policies().freeze(operation)); + assertThat(fixture.tx(() -> fixture.policies().freeze(operation)).canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + assertThat(fixture.reads().readCapture(operation).orElseThrow().canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT outcome FROM game_design_publication_operation WHERE publish_workflow_id = ?", + operation.workflowId()), + "reserved publication fixture must have its persisted operation row") + .get(0, String.class)) + .isEqualTo("PENDING"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_snapshot SET snapshot_json = snapshot_json"))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void freezeAndSourceWriterUseSameVersionLockAndRollbackDoesNotLeaveCapture() throws Exception { + var fixture = retainedFixture(true); + var operation = publication(fixture); + fixture + .write() + .executeWithoutResult( + status -> { + fixture.policies().freeze(operation); + status.setRollbackOnly(); + }); + assertThat(fixture.reads().readCapture(operation)).isEmpty(); + var frozen = new CountDownLatch(1); + var release = new CountDownLatch(1); + var attempting = new CountDownLatch(1); + var freezerPid = new java.util.concurrent.atomic.AtomicInteger(); + var writerPid = new java.util.concurrent.atomic.AtomicInteger(); + try (var executor = Executors.newFixedThreadPool(2)) { + var freezer = + executor.submit( + () -> + fixture.tx( + () -> { + var result = fixture.policies().freeze(operation); + freezerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "freezer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + frozen.countDown(); + await(release); + return result; + })); + assertThat(frozen.await(10, TimeUnit.SECONDS)).isTrue(); + var writer = + executor.submit( + () -> + fixture.tx( + () -> { + writerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "writer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + // Acquire the exact Version lock used by the repository's source writer + // before exercising the storage guard, independently of creator preflight. + fixture + .dsl() + .fetchOne( + "SELECT id FROM version WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '2' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + })); + assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); + boolean observedVersionBlock = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var activity = + fixture + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' " + + "AND query LIKE 'SELECT id FROM version%FOR UPDATE%' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + freezerPid.get(), writerPid.get()); + if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { + observedVersionBlock = true; + break; + } + Thread.sleep(25); + } + assertThat(observedVersionBlock) + .as("writer backend blocked by freezer on the exact Version SELECT FOR UPDATE") + .isTrue(); + release.countDown(); + assertThat(freezer.get(10, TimeUnit.SECONDS).snapshot().policies()).hasSize(1); + assertThatThrownBy(() -> writer.get(10, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .rootCause() + .hasMessageContaining("realm policy source is frozen"); + } finally { + release.countDown(); + } + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne("SELECT source_epoch FROM game_design_realm_policy_source"), + "retained Version fixture must have its realm-policy source row") + .get(0, String.class)) + .isEqualTo("1"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("ISOLATED fixture latch timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private static void start(Fixture fixture, DraftCommitBinding binding) { + fixture.tx( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); + } + + private static void synchronize( + Fixture fixture, DraftCommitBinding binding, RealmPolicyApplication result) { + fixture.tx( + () -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(result.ownerOutcome()))); + fixture.policies().captureSynchronized(binding); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + } + + private static GameDesignPublicationOperation publication(Fixture fixture) { + return fixture.tx( + () -> { + try { + // Existing fixture stipulates actual World and Account producer bytes; it runs GD's + // real + // disjoint World commit, selection, attempt and operation repositories. Capture + // integration + // here is isolated in the same transaction, not a claim of normal producer composition. + var operation = + IsolatedPublicationOwnerSetup.retain(fixture.dsl(), fixture.target(), 1); + fixture + .policies() + .captureSynchronized(operation.account().input().selection().selectedCommit()); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private static DraftCommitBinding policyBinding( + TargetProof target, String epoch, String realm, boolean production) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-" + + realm + + "\",\"policy\":" + + policy.canonicalJson() + + "}"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-explicit-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + epoch))); + } + + private static Fixture freshFixture() { + String schema = "gd_policy_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target("54") + .load() + .migrate(); + var transactions = new DataSourceTransactionManager(dataSource); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var target = + write.execute( + status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED policy source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return target(version); + }); + var baseline = policyBinding(target, "0", "main", true); + var policies = new RealmPolicySourceRepository(dsl); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + return new Fixture( + dsl, + write, + target, + baseline, + policies, + coordinator, + new RealmPolicySourceService(policies, transactions)); + } + + private static Fixture retainedFixture(boolean isolatedBaseline) { + String schema = "gd_policy_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + migrate(dataSource, schema, "51"); + var transactions = new DataSourceTransactionManager(dataSource); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var game = + write.execute( + status -> { + var created = new Game(); + created.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + created.setName("ISOLATED retained policy source"); + return new GameRepository(dsl).save(created); + }); + var version = write.execute(status -> insertRetainedVersion(dsl, properties, game, 1)); + migrate(dataSource, schema, "54"); + var target = target(version); + var baseline = policyBinding(target, "0", "main", true); + var policies = new RealmPolicySourceRepository(dsl); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var fixture = + new Fixture( + dsl, + write, + target, + baseline, + policies, + coordinator, + new RealmPolicySourceService(policies, transactions)); + if (isolatedBaseline) { + fixture.tx( + () -> { + // Explicit ISOLATED assumption: prior authenticated owner creation supplied this actual + // complete policy source/epoch. There is intentionally no production initializer API. + coordinator.claim(baseline); + coordinator.claimApplicationSlot(baseline); + coordinator.markOwnerInProgress(baseline, Owner.GAME_DESIGN_CONTROL_PLANE); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + baseline.commitId(), + baseline.digest(), + "ISOLATED-initial-owner-baseline", + "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + BigInteger.ONE.toString()))); + coordinator.recordOwnerOutcome(baseline, outcome); + coordinator.advanceVisibilityFence( + baseline, + new DraftCommitCoordinatorRepository.CoordinatorProof(baseline, List.of(outcome))); + coordinator.releaseApplicationSlot(baseline); + var policy = RealmPolicySource.revision(baseline, baseline.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(baseline, "1", List.of(policy)); + dsl.execute( + "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + baseline.commitId(), + baseline.requestId(), + snapshot.canonicalJson()); + dsl.execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + baseline.commitId()); + return null; + }); + } + return fixture; + } + + private static void migrate(DriverManagerDataSource dataSource, String schema, String target) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target(target) + .load() + .migrate(); + } + + private static Version insertRetainedVersion( + DSLContext dsl, PostgresProperties properties, Game game, int versionNumber) { + var inserted = + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " + + "'ISOLATED retained source fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + versionNumber, + game.getId()); + if (inserted == null) { + throw new IllegalStateException("ISOLATED retained Game Design source row is absent"); + } + return new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + TargetProof target, + DraftCommitBinding baseline, + RealmPolicySourceRepository policies, + DraftCommitCoordinatorRepository coordinator, + RealmPolicySourceService reads) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..8a7c419329 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -0,0 +1,1254 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.ForwardingServerCall; +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.ByteArrayOutputStream; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +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.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Actual GD owner DB guard proof; every upstream creator/source/freeze input is ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignPublicationOperationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static final AtomicLong TEST_CERTIFICATE_SERIAL = new AtomicLong(1); + + /** + * Genuine GD SQL result and physical workload identity; upstream creator/export/freeze remain + * ISOLATED. + */ + @Test + void + physicalMtlsTerminalReadRecoversActualPublishedAndNoPublicationOwnerSealsAndRejectsWrongPeers( + @TempDir Path directory) throws Exception { + var pki = publicationReadPki(); + int ownerIndex = 0; + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + byte[] retained = original.terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var headers = new AtomicInteger(); + var loseResponse = new AtomicBoolean(true); + var server = publicationReadServer(fixture, pki.server(), pki.ca(), headers, loseResponse); + try { + try (var client = + publicationReadClient( + server, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-account"))) { + client.init(); + // The real handler and owner read finish; the first outbound result is deliberately lost. + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + var recovered = client.read(request).terminalEvidence().orElseThrow(); + assertThat(recovered.canonicalBytes()).isEqualTo(retained); + assertThat(recovered.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + assertThat(recovered.outcome().name()) + .isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + if (published) { + assertThat(recovered.publicationVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(recovered.publishedReleaseBundleDigest()) + .isEqualTo(recovered.releaseContent().contentDigest()); + } else + assertThatThrownBy(recovered::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); + assertThat(client.read(request).terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo(retained); + } + for (var identity : + java.util.List.of(pki.wrongCallerService(), pki.wrongCallerNamespace())) { + try (var client = + publicationReadClient( + server, + identity, + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + identity.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + } + } + assertThat(headers).hasValue(5); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + for (var wrongServer : + java.util.List.of(pki.wrongServerService(), pki.wrongServerNamespace())) { + var deniedHeaders = new AtomicInteger(); + var deniedServer = + publicationReadServer( + fixture, wrongServer, pki.ca(), deniedHeaders, new AtomicBoolean(false)); + try (var client = + publicationReadClient( + deniedServer, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + wrongServer.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + assertThat(deniedHeaders).hasValue(0); + } finally { + deniedServer.shutdownNow(); + assertThat(deniedServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isEqualTo(retained); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + ownerIndex++; + } + } + + private Server publicationReadServer( + Fixture fixture, + TestCertificate identity, + X509Certificate ca, + AtomicInteger headers, + AtomicBoolean loseResponse) + throws Exception { + ServerInterceptor responseLoss = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean dropped; + + @Override + public void sendMessage(RespT message) { + if (loseResponse.compareAndSet(true, false)) dropped = true; + else super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + super.close( + dropped + ? Status.UNAVAILABLE.withDescription( + "ISOLATED lost terminal read response") + : status, + trailers); + } + }, + metadata); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(ca) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new GameDesignPublicationTerminalReadGrpcService(fixture.service(), "test"), + responseLoss, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameDesignPublicationTerminalClient publicationReadClient( + Server server, TestCertificate identity, X509Certificate ca, Path directory) + throws Exception { + Files.createDirectories(directory); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + publicationReadPem( + directory.resolve("client.crt"), "CERTIFICATE", identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + publicationReadPem( + directory.resolve("client.key"), "PRIVATE KEY", identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + publicationReadPem(directory.resolve("ca.crt"), "CERTIFICATE", ca.getEncoded()).toString()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new GameDesignPublicationTerminalClient( + endpoints, tls, new GrpcChannelFactory(), "test"); + } + + private static Path publicationReadPem(Path path, String type, byte[] bytes) throws Exception { + Files.writeString( + path, + "-----BEGIN " + + type + + "-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes) + + "\n-----END " + + type + + "-----\n"); + return path; + } + + private static TestPki publicationReadPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + Security.addProvider(new BouncyCastleProvider()); + var keys = publicationReadKeyPair(); + var name = new X500Name("CN=Game Design PostgreSQL Terminal Test CA, O=FireMUD Test"); + var ca = + publicationReadCertificate(name, keys.getPublic(), name, keys.getPrivate(), true, null); + return new TestPki( + ca, + publicationReadLeaf( + name, keys.getPrivate(), "server", "spiffe://firemud/ns/test/sa/game-design-service"), + publicationReadLeaf( + name, keys.getPrivate(), "account", "spiffe://firemud/ns/test/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-namespace", + "spiffe://firemud/ns/other/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-service", + "spiffe://firemud/ns/test/sa/world-management-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-namespace", + "spiffe://firemud/ns/other/sa/game-design-service")); + } + + private static TestCertificate publicationReadLeaf( + X500Name ca, PrivateKey issuerKey, String label, String uri) throws Exception { + var keys = publicationReadKeyPair(); + var names = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, uri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + return new TestCertificate( + label, + keys.getPrivate(), + publicationReadCertificate( + new X500Name("CN=" + label + ", O=FireMUD Test"), + keys.getPublic(), + ca, + issuerKey, + false, + names)); + } + + private static X509Certificate publicationReadCertificate( + X500Name subject, + java.security.PublicKey key, + X500Name issuer, + PrivateKey issuerKey, + boolean ca, + GeneralNames names) + throws Exception { + var start = Instant.now().minusSeconds(60); + var builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(TEST_CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(start), + Date.from(start.plusSeconds(60L * 60L * 24L * 14L)), + subject, + key); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage( + ca + ? KeyUsage.keyCertSign | KeyUsage.cRLSign + : KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + if (!ca) { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, names); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey))); + } + + private static KeyPair publicationReadKeyPair() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate( + String label, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate ca, + TestCertificate server, + TestCertificate account, + TestCertificate wrongCallerService, + TestCertificate wrongCallerNamespace, + TestCertificate wrongServerService, + TestCertificate wrongServerNamespace) {} + + @Test + void authenticatedTerminalReadDispatchesActualStoredPublishedAndNoPublicationEvidence() + throws Exception { + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var expected = + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + for (String peer : java.util.List.of("account-service", "world-management-service")) { + var result = readThroughHandler(fixture, request, peer); + assertThat(result.error).isNull(); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, result.response); + assertThat(evidence.terminalEvidence().orElseThrow().canonicalBytes()).isEqualTo(expected); + assertThat(evidence.status().name()).isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + } + } + } + + @Test + void authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation() throws Exception { + var fixture = fixture(); + var pending = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var result = readThroughHandler(fixture, pending, "world-management-service"); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(pending, result.response); + assertThat(evidence.status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(evidence.terminalEvidence()).isEmpty(); + var absentOperation = + IsolatedPublicationOperationFixtures.fresh( + fixture.operation().account().input().selection().target()); + var absent = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", absentOperation.canonicalBytes()); + var absentResult = readThroughHandler(fixture, absent, "account-service"); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(absent, absentResult.response) + .status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + + @Test + void retainedV50TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() + throws Exception { + var fixture = fixture("50"); + assertThat(fixture.candidate()).isNull(); + var op = fixture.operation(); + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "NO_PUBLICATION"); + // V50 framed nullable release_row_json as a present, zero-byte fourth frame for + // NO_PUBLICATION. Preserve that historical encoding exactly without routing an empty value + // through the nonempty canonical-text helper. + DraftAuthorizationFenceBinding.frame(old, new byte[0]); + fixture + .write() + .executeWithoutResult( + status -> { + var attempt = + fixture + .attempts() + .findByPublishWorkflowIdForUpdate(op.workflowId()) + .orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + fixture.attempts().save(attempt); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + op.workflowId()); + }); + fixture.completeMigration().run(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create("test", op.canonicalBytes()); + var result = readThroughHandler(fixture, request, "account-service"); + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + var retained = fixture.service().readExact(op).orElseThrow(); + assertThat(retained.receiptBytes()).isEqualTo(old.toByteArray()); + assertThat(retained.terminalEvidenceBytes()).isNull(); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT publication_version_state_epoch FROM game_design_publication_operation WHERE publish_workflow_id = ?", + op.workflowId())) + .get(0)) + .isNull(); + } + + private ReadCollector readThroughHandler( + Fixture fixture, + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + String service) { + var handler = new GameDesignPublicationTerminalReadGrpcService(fixture.service(), "test"); + var collector = new ReadCollector(); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + service, "test", service)); + var previous = context.attach(); + try { + handler.readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), collector); + } finally { + context.detach(previous); + } + return collector; + } + + private static final class ReadCollector + implements StreamObserver { + private ReadGameDesignPublicationTerminalResponse response; + private Status.Code error; + + @Override + public void onNext(ReadGameDesignPublicationTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final String ASSET_FILE_NAME = "publication-operation-logo.png"; + private static final String ASSET_CONTENT_TYPE = "image/png"; + private static final byte[] ASSET_BYTES = + "isolated publication asset bytes".getBytes(StandardCharsets.UTF_8); + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + + @Test + void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() + throws Exception { + var fixture = fixture(); + noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); + var noPublication = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + assertThat(noPublication.outcome()) + .isEqualTo(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + assertThatThrownBy(noPublication::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .operations() + .requirePending( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SEALED_OR_CHANGED"); + assertThatThrownBy( + () -> fixture.write().executeWithoutResult(status -> rawReleaseInsert(fixture))) + .hasMessageContaining("selected publication is absent, sealed, or changed"); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + } + + @Test + void terminalEvidenceKeepsOriginalCommittedEpochAfterLaterVersionTransition() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + long captured = terminal.publicationVersionStateEpoch(); + assertThat(captured).isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(terminal.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + fixture + .write() + .executeWithoutResult( + status -> { + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(captured + 1); + fixture.versions().save(version); + }); + var replay = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(replay.terminalEvidenceBytes()) + .publicationVersionStateEpoch()) + .isEqualTo(captured); + } + + @Test + void terminalExtensionRefusesRawEpochDigestBytesAndReleaseContentSubstitution() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + for (String assignment : + java.util.List.of( + "publication_version_state_epoch = publication_version_state_epoch + 1", + "published_release_bundle_digest = 'sha256:' || repeat('f', 64)", + "terminal_evidence_bytes = terminal_evidence_bytes || decode('00', 'hex')", + "release_content_bytes = release_content_bytes || decode('00', 'hex')")) { + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET " + + assignment + + " WHERE publish_workflow_id = ?", + fixture.operation().workflowId()))) + .isInstanceOf(RuntimeException.class); + } + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes()) + .isEqualTo(original.terminalEvidenceBytes()); + } + + @Test + void originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows() throws Exception { + for (String forgedField : java.util.List.of("epoch", "digest", "content", "terminal")) { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture, false); + rawTerminalSeal(fixture, forgedField); + })) + .isInstanceOf(RuntimeException.class); + var pending = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(pending.outcome()).isEqualTo("PENDING"); + assertThat(pending.terminalEvidenceBytes()).isNull(); + publish(fixture); + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isNotNull(); + } + } + + @Test + void publicationSealEpochMustRemainTheActualVersionEpochThroughCommit() throws Exception { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + fixture + .dsl() + .execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE tenant_id = ? AND id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()); + })) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + + @Test + void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() + throws Exception { + var fixture = fixture(); + var staleFailure = + fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("PUBLISHED"); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + staleFailure.setStatus(PublishAttemptStatus.FAILED); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult(status -> fixture.attempts().save(staleFailure))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("CAS_CONFLICT"); + assertThatThrownBy(() -> noPublication(fixture)).isInstanceOf(IllegalStateException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + } + + @Test + void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() + throws Exception { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + throw new IllegalStateException( + "ISOLATED rollback after all owner writes"); + })) + .hasMessageContaining("rollback after all owner writes"); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat( + fixture + .attempts() + .findByPublishWorkflowId(fixture.operation().workflowId()) + .orElseThrow() + .getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + publish(fixture); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PUBLISHED"); + } + + @Test + void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exception { + var fixture = fixture(); + var sealed = new CountDownLatch(1); + var releaseSeal = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var winner = + executor.submit( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + noPublicationInTransaction(fixture); + sealed.countDown(); + await(releaseSeal); + })); + assertThat(sealed.await(10, TimeUnit.SECONDS)).isTrue(); + var loser = + executor.submit( + () -> { + assertThatThrownBy(() -> publish(fixture)) + .isInstanceOf(IllegalStateException.class); + }); + releaseSeal.countDown(); + winner.get(10, TimeUnit.SECONDS); + loser.get(10, TimeUnit.SECONDS); + } finally { + releaseSeal.countDown(); + } + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("NO_PUBLICATION"); + } + + private void noPublication(Fixture fixture) { + fixture.write().executeWithoutResult(status -> noPublicationInTransaction(fixture)); + } + + private void noPublicationInTransaction(Fixture fixture) { + var op = fixture.operation(); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_BUSINESS_DENIAL"); + fixture.attempts().save(attempt); + // Emulate the historical V50/V51 seal storage directly. The current attempt wrapper also + // writes the V53 realm-policy association, which is absent from these schemas. + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), false); + } + + private void publish(Fixture fixture) { + fixture.write().executeWithoutResult(status -> publishInTransaction(fixture)); + } + + private void publishInTransaction(Fixture fixture) { + publishInTransaction(fixture, true); + } + + private void publishInTransaction(Fixture fixture, boolean seal) { + var op = fixture.operation(); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + fixture.releases().save(bundle(fixture)); + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(version.getVersionStateEpoch() + 1); + fixture.versions().save(version); + var artifact = + fixture + .artifacts() + .findByTenantIdAndVersionIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + fixture.artifacts().save(artifact); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + fixture.attempts().save(attempt); + if (seal) { + // Emulate the historical V50/V51 seal storage without querying the V53 policy association. + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + } + } + + /** + * Attempts a raw first seal, so failures prove content/epoch binding rather than only + * immutability. + */ + private void rawTerminalSeal(Fixture fixture, String forgedField) { + var op = fixture.operation(); + var row = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence, publication_release_content(r) AS content, 'sha256:' || encode(sha256(publication_release_content(r)), 'hex') AS digest FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + op.tenantKey(), + op.versionId())); + String evidence = row.get("evidence", String.class); + byte[] content = row.get("content", byte[].class); + String digest = row.get("digest", String.class); + long epoch = op.world().request().versionStateEpoch() + 1; + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(old, evidence); + var terminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(terminal, "game-design-publication-terminal/v1"); + DraftAuthorizationFenceBinding.frame(terminal, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(terminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(terminal, content); + DraftAuthorizationFenceBinding.frame(terminal, Long.toString(epoch)); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'PUBLISHED', revision = revision + 1, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + evidence, + forgedField.equals("terminal") ? new byte[] {1} : terminal.toByteArray(), + forgedField.equals("epoch") ? epoch + 1 : epoch, + forgedField.equals("content") ? new byte[] {1} : content, + forgedField.equals("digest") ? "sha256:" + "f".repeat(64) : digest, + op.workflowId()); + } + + private PublishedReleaseBundle bundle(Fixture fixture) { + var op = fixture.operation(); + var bundle = new PublishedReleaseBundle(); + bundle.setTenantId(op.tenantKey()); + bundle.setVersionId(op.versionId()); + bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(op.account().tenantId()); + bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(op.workflowId()); + bundle.setManifestHash(fixture.candidate().manifestHash()); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson( + new ObjectMapper().writeValueAsString(fixture.candidate().artifactDigests())); + bundle.setRequiredManifestAssetKeysJson( + new ObjectMapper().writeValueAsString(fixture.candidate().requiredManifestAssetKeys())); + bundle.setCommandDefinitionsJson("[]"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants(op.versionId(), op.world()))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private void rawReleaseInsert(Fixture fixture) { + var bundle = bundle(fixture); + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, attestation_schema_version, publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, " + + "artifact_digests_json, required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, world_published_start_location_evidence_json) " + + "VALUES (?, ?, 1, ?, ?, ?, 'v2', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + bundle.getTenantId(), + bundle.getVersionId(), + bundle.getCanonicalTenantId(), + bundle.getCanonicalVersionId(), + UUID.randomUUID().toString(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getGenerationConfigRevision(), + bundle.getParticipantDigestsJson(), + bundle.getWorldPublishedStartLocationEvidenceJson()); + } + + private Fixture fixture() throws Exception { + return fixture("51"); + } + + private Version insertRetainedVersion( + DSLContext dsl, VersionRepository versions, Game game, int versionNumber) { + var inserted = + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " + + "'ISOLATED retained publication operation fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + versionNumber, + game.getId()); + if (inserted == null) { + throw new IllegalStateException("ISOLATED retained Game Design owner row is absent"); + } + return versions.findById(inserted.get("id", Long.class)).orElseThrow(); + } + + private Fixture fixture(String migrationTarget) throws Exception { + String schema = "gd_pub_op_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target(migrationTarget) + .load() + .migrate(); + var transactions = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var configuration = new org.jooq.impl.DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set( + new org.jooq.impl.DataSourceConnectionProvider( + new TransactionAwareDataSourceProxy(source))); + configuration.set( + new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(transactions)); + var dsl = DSL.using(configuration); + var games = new GameRepository(dsl); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var versions = new VersionRepository(dsl); + Game game = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED publication owner"); + return games.save(requested); + }); + // These V50/V51 cases model retained history. Insert the canonical owner row before V52 so + // the current VersionRepository does not enroll it in post-V51 source storage. + Version version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var operation = + write.execute( + status -> { + try { + return IsolatedPublicationOwnerSetup.retain( + dsl, target, version.getVersionStateEpoch()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var operations = new GameDesignPublicationOperationRepository(dsl); + ExportedAssetManifest readCandidate = null; + if (!"50".equals(migrationTarget)) { + var gameAssets = new GameAssetRepository(dsl); + var asset = + write.execute( + status -> { + var requested = new GameAsset(); + requested.setTenantId(game.getTenantId()); + requested.setFileName(ASSET_FILE_NAME); + requested.setContentType(ASSET_CONTENT_TYPE); + requested.setData(ASSET_BYTES); + return gameAssets.save(requested); + }); + var publicationRepository = new VersionAssetPublicationRepository(dsl); + var publicationService = + new VersionAssetPublicationServiceImpl(transactions, publicationRepository); + publicationService.associateDraftAsset( + game.getTenantId(), version.getId(), asset.getId(), "logo"); + var snapshot = + publicationService.freezeOrReadSnapshot(game.getTenantId(), version.getVersionNumber()); + var artifactService = + new VersionAssetArtifactServiceImpl( + new VersionAssetArtifactRepository(dsl), + null, + versions, + null, + null, + null, + null, + null, + new ObjectMapper()); + write.execute( + status -> + artifactService.stageExport( + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + var artifacts = new VersionAssetArtifactRepository(dsl); + var candidateService = + new VersionAssetExportCandidateServiceImpl( + versions, + games, + new PublishAttemptRepository(dsl), + artifacts, + publicationService, + transactions, + new ObjectMapper()); + var requestedCandidate = candidate(snapshot); + var committedCandidate = + candidateService.recordExportCandidate( + game.getTenantId(), version.getVersionNumber(), requestedCandidate); + readCandidate = + candidateService.readExportCandidate(game.getTenantId(), version.getVersionNumber()); + assertThat(committedCandidate).isEqualTo(requestedCandidate); + assertThat(readCandidate).isEqualTo(committedCandidate); + } + var artifacts = new VersionAssetArtifactRepository(dsl); + return new Fixture( + dsl, + write, + versions, + new PublishAttemptRepository(dsl), + new PublishedReleaseBundleRepository(dsl), + artifacts, + operations, + new GameDesignPublicationOperationService(operations, transactions), + operation, + readCandidate, + () -> + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate()); + } + + private ExportedAssetManifest candidate( + VersionAssetPublicationRepository.ExportSnapshot snapshot) { + var source = snapshot.items().get(0); + String contentDigest = source.contentDigest(); + String objectKey = "artifacts/sha256/" + contentDigest.substring("sha256:".length()); + var digest = + new PublishedArtifactDigest( + source.usageKey(), "BINARY", objectKey, contentDigest, source.contentType(), 1); + String url = PUBLIC_BASE_URL + "/" + objectKey; + String manifestJson = + "{\"schemaVersion\":1,\"assets\":{\"" + + source.usageKey() + + "\":{\"usageKey\":\"" + + source.usageKey() + + "\",\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + objectKey + + "\",\"contentDigest\":\"" + + contentDigest + + "\",\"contentType\":\"" + + source.contentType() + + "\",\"artifactSchemaVersion\":1,\"producerService\":\"game-design-service\",\"versionId\":\"" + + snapshot.canonicalVersionId() + + "\",\"url\":\"" + + url + + "\"}}}"; + return new ExportedAssetManifest( + sha256(manifestJson.getBytes(StandardCharsets.UTF_8)), + 1, + List.of(source.usageKey()), + List.of(digest)); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("ISOLATED barrier timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + VersionRepository versions, + PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, + VersionAssetArtifactRepository artifacts, + GameDesignPublicationOperationRepository operations, + GameDesignPublicationOperationService service, + GameDesignPublicationOperation operation, + ExportedAssetManifest candidate, + Runnable completeMigration) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java new file mode 100644 index 0000000000..349d624859 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -0,0 +1,778 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +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.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySnapshot; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListener; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.Test; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Actual Game Design terminal and release rows; the retained policy baseline is ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class RealmPolicyPublicationPostgresIntegrationTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final List PUBLISHED_SET_COLUMNS = + List.of( + "canonical_tenant_id", + "canonical_version_id", + "game_design_version_row_id", + "version_number", + "source_commit_id", + "source_epoch", + "target_proof_json", + "operation_bytes", + "capture_bytes", + "terminal_evidence_bytes", + "release_content_bytes", + "published_release_bundle_ref", + "published_release_bundle_digest", + "publish_workflow_id", + "manifest_hash", + "publication_version_state_epoch", + "policy_count", + "policy_set_digest", + "sealed"); + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void actualSealAssociatesCompleteSetAndReadKeepsOriginalEpochAfterVersionMovement() + throws Exception { + Fixture fixture = fixture(true); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, false); + + var original = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(original.policies()).hasSize(1); + assertThat(original.policyCount()).isEqualTo(1); + assertThat(original.policies().getFirst().policyId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(original.policies().getFirst().source().revisionId()) + .isEqualTo(fixture.baseline().revisions().getFirst().revisionId()); + assertThat(original.policies().getFirst().source().commitId()) + .isEqualTo(fixture.baseline().commitId()); + assertThat(original.publishWorkflowId()).isEqualTo(operation.workflowId()); + assertThat(original.publicationVersionStateEpoch()) + .isEqualTo(operation.world().request().versionStateEpoch() + 1); + assertRejectedHeaderClonesPreserveOriginal(fixture, original); + + var exactRetry = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertThat(exactRetry.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat(exactRetry.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(exactRetry.operationBytes()).containsExactly(original.operationBytes()); + assertThat(exactRetry.captureBytes()).containsExactly(original.captureBytes()); + assertThat(exactRetry.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + + fixture.moveVersion(VersionLifecycleState.ACTIVE, original.publicationVersionStateEpoch() + 1); + var activeRead = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(activeRead.publicationVersionStateEpoch()) + .isEqualTo(original.publicationVersionStateEpoch()); + assertThat(activeRead.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat( + fixture + .publicationReads() + .readPublishedPolicy(fixture.target(), "world", "main") + .orElseThrow() + .policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + var retryAfterActivation = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertThat(retryAfterActivation.policies().getFirst().policyId()) + .isEqualTo(original.policies().getFirst().policyId()); + assertThat(retryAfterActivation.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(retryAfterActivation.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_published_realm_policy_set " + + "SET policy_set_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + "sha256:" + "f".repeat(64), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void openSetRejectsReplacedSourceAndWrongOrdinalWhileKeepingInheritedProvenance() + throws Exception { + Fixture fixture = fixture(true); + var stale = + fixture + .policySource() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow() + .policies() + .getFirst(); + // A second stipulated ISOLATED owner baseline replaces the main policy. The genuine + // publication selection then inherits it through the ordinary frozen-source path. + var replacementBinding = + fixture.tx(() -> baseline(fixture.target(), fixture.dsl(), "1", "Replacement World")); + GameDesignPublicationOperation operation = fixture.prepare(true); + var selected = fixture.policySource().readCapture(operation).orElseThrow().snapshot(); + var replacement = selected.policies().getFirst(); + assertThat(selected.binding().commitId()).isNotEqualTo(replacementBinding.commitId()); + assertThat(replacement.commitId()).isEqualTo(replacementBinding.commitId()); + assertThat(replacement.revisionId()) + .isEqualTo(replacementBinding.revisions().getFirst().revisionId()); + + var probes = new AtomicInteger(); + var configuration = fixture.dsl().configuration(); + var previousListeners = configuration.executeListenerProviders(); + configuration.set( + new DefaultExecuteListenerProvider( + new ExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.startsWith("INSERT INTO game_design_published_realm_policy_set ")) + return; + assertRejectedOpenSetPolicy(fixture, operation, stale, 0); + assertRejectedOpenSetPolicy(fixture, operation, replacement, 1); + probes.incrementAndGet(); + } + })); + try { + fixture.writePublish(operation, false); + } finally { + configuration.set(previousListeners); + } + assertThat(probes.get()).isEqualTo(1); + var published = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(published.sourceCommitId()).isEqualTo(selected.binding().commitId()); + assertThat(published.policies()).hasSize(1); + assertThat(published.policies().getFirst().source()).isEqualTo(replacement); + var retry = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertPublishedSetUnchanged(published, retry); + assertPublishedSetUnchanged( + published, fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow()); + } + + private static void assertRejectedOpenSetPolicy( + Fixture fixture, + GameDesignPublicationOperation operation, + RealmPolicySource.Policy source, + int ordinal) { + var policy = source.policy(); + UUID policyId = UUID.randomUUID(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + fixture + .operations() + .read(operation.workflowId()) + .orElseThrow() + .terminalEvidenceBytes()); + var release = terminal.releaseContent(); + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, + fixture.target(), + release.versionNumber(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source); + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + nested -> + DSL.using(nested) + .execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + ordinal, + policyId, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + digest, + policy.visible(), + policy.publicProduction()))) + .satisfies( + failure -> + assertThat(rootCause(failure).getMessage()) + .contains( + "published realm policy row differs from exact captured source revision")); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))).isZero(); + } + + @Test + void sealRollbackLeavesNoAssociationAndExactPublicationRetryAllocatesOneStableIdentity() + throws Exception { + Fixture fixture = fixture(true); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, true); + + assertThat(fixture.operations().read(operation.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))).isZero(); + + fixture.writePublish(operation, false); + var first = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + fixture.tx(() -> fixture.publicationWrites().retainSealedPublished(operation.workflowId())); + var replay = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(replay.policies().getFirst().policyId()) + .isEqualTo(first.policies().getFirst().policyId()); + assertThat(replay.policySetDigest()).isEqualTo(first.policySetDigest()); + } + + @Test + void releaseWithoutTypedSourceRemainsValidButMissingCaptureWithSourceFailsClosed() + throws Exception { + Fixture unrelated = fixture(false); + GameDesignPublicationOperation noPolicy = unrelated.prepare(false); + unrelated.writePublish(noPolicy, false); + assertThat(unrelated.publicationReads().readPublishedSet(unrelated.target())).isEmpty(); + assertThat( + unrelated.tx( + () -> unrelated.publicationWrites().retainSealedPublished(noPolicy.workflowId()))) + .isEmpty(); + + Fixture missingCapture = fixture(true); + GameDesignPublicationOperation policyOperation = missingCapture.prepare(false); + assertThatThrownBy(() -> missingCapture.writePublish(policyOperation, false)) + .hasMessageContaining("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + assertThat( + missingCapture.operations().read(policyOperation.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat(missingCapture.publicationReads().readPublishedSet(missingCapture.target())) + .isEmpty(); + } + + private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception { + String schema = "gd_realm_policy_pub_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + migrate(source, schema, "51"); + var transactions = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var configuration = new DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(source))); + configuration.set(new SpringTransactionProvider(transactions)); + var dsl = DSL.using(configuration); + var games = new GameRepository(dsl); + var properties = new PostgresProperties(); + properties.setSchema(schema); + var versions = new VersionRepository(dsl); + Game game = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED realm policy publication"); + return games.save(requested); + }); + Version version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); + migrate(source, schema, "54"); + TargetProof target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var policySource = new RealmPolicySourceRepository(dsl); + var baseline = isolatedPolicyBaseline ? write.execute(status -> baseline(target, dsl)) : null; + var publicationWrites = new RealmPolicyPublicationRepository(dsl); + var publicationReads = new RealmPolicyPublicationService(publicationWrites, transactions); + return new Fixture( + dsl, + write, + transactions, + target, + baseline, + versions, + new PublishAttemptRepository(dsl), + new PublishedReleaseBundleRepository(dsl), + new GameDesignPublicationOperationRepository(dsl), + policySource, + publicationWrites, + publicationReads); + } + + private static void migrate(DriverManagerDataSource source, String schema, String target) { + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .target(target) + .load() + .migrate(); + } + + private static Version insertRetainedVersion( + DSLContext dsl, VersionRepository versions, Game game, int versionNumber) { + var inserted = + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " + + "'ISOLATED retained policy publication fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + versionNumber, + game.getId()); + if (inserted == null) { + throw new IllegalStateException("ISOLATED retained Game Design owner row is absent"); + } + return versions.findById(inserted.get("id", Long.class)).orElseThrow(); + } + + private static DraftCommitBinding baseline(TargetProof target, DSLContext dsl) { + return baseline(target, dsl, "0", "World"); + } + + private static DraftCommitBinding baseline( + TargetProof target, DSLContext dsl, String expectedEpoch, String worldDisplayName) { + DraftCommitBinding binding = policyBinding(target, expectedEpoch, worldDisplayName); + String sourceEpoch = Long.toString(Long.parseLong(expectedEpoch) + 1); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-initial-policy-baseline", + "ISOLATED-test-owner-baseline".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch, + sourceEpoch))); + coordinator.recordOwnerOutcome(binding, outcome); + IsolatedPublicationOwnerSetup.advanceIsolatedVisibility(dsl, binding, List.of(outcome)); + coordinator.releaseApplicationSlot(binding); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); + dsl.execute( + "INSERT INTO game_design_realm_policy_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) " + + "VALUES (?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.commitId(), + binding.requestId(), + snapshot.canonicalJson()); + if ("0".equals(expectedEpoch)) { + dsl.execute( + "INSERT INTO game_design_realm_policy_source " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) " + + "VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + sourceEpoch, + binding.commitId()); + } else { + dsl.execute( + "UPDATE game_design_realm_policy_source SET source_epoch = ?, visible_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + sourceEpoch, + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId()); + } + return binding; + } + + private static DraftCommitBinding policyBinding( + TargetProof target, String expectedEpoch, String worldDisplayName) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"" + + worldDisplayName + + "\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"isolated-main\",\"policy\":" + + policy.canonicalJson() + + "}"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-initial-source-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch))); + } + + private static void assertRejectedHeaderClonesPreserveOriginal( + Fixture fixture, RealmPolicyPublishedEvidence.PublishedSet original) { + String targetProofError = "published realm policy set requires a closed complete TargetProof"; + String terminalBindingError = + "published realm policy set is not bound to exact sealed operation, capture, source, and release"; + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "jsonb_set(existing.target_proof_json::JSONB, '{sourceGameRowId}', 'null'::JSONB)::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "(existing.target_proof_json::JSONB - 'canonicalVersionId')::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "target_proof_json", + "(existing.target_proof_json::JSONB || '{\"unknown\":\"x\"}'::JSONB)::TEXT", + targetProofError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "operation_bytes", + "existing.operation_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "terminal_evidence_bytes", + "existing.terminal_evidence_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "capture_bytes", + "existing.capture_bytes || decode('00', 'hex')", + terminalBindingError); + assertRejectedHeaderClonePreservesOriginal( + fixture, + original, + "publish_workflow_id", + "('wrong-' || existing.publish_workflow_id)::VARCHAR(1024)", + "published realm policy set operation is unavailable"); + } + + private static void assertRejectedHeaderClonePreservesOriginal( + Fixture fixture, + RealmPolicyPublishedEvidence.PublishedSet original, + String replacementColumn, + String replacementExpression, + String expectedGuardMessage) { + String headerBefore = publishedSetRowJson(fixture); + List policiesBefore = publishedPolicyRowsJson(fixture); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))) + .isEqualTo(original.policyCount()); + + String sql = headerCloneInsertSql(replacementColumn, replacementExpression); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture + .dsl() + .execute( + sql, + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return null; + })) + .satisfies( + failure -> assertThat(rootCause(failure).getMessage()).contains(expectedGuardMessage)); + + assertThat(publishedSetRowJson(fixture)).isEqualTo(headerBefore); + assertThat(publishedPolicyRowsJson(fixture)).containsExactlyElementsOf(policiesBefore); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy_set"))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))) + .isEqualTo(original.policyCount()); + assertPublishedSetUnchanged( + original, fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow()); + } + + private static String headerCloneInsertSql( + String replacementColumn, String replacementExpression) { + if (!PUBLISHED_SET_COLUMNS.contains(replacementColumn)) { + throw new IllegalArgumentException("Published-set clone column is not allowlisted"); + } + String columnList = String.join(", ", PUBLISHED_SET_COLUMNS); + String selectList = + PUBLISHED_SET_COLUMNS.stream() + .map( + column -> { + if ("sealed".equals(column)) return "FALSE"; + if (column.equals(replacementColumn)) return replacementExpression; + return "existing." + column; + }) + .collect(java.util.stream.Collectors.joining(", ")); + return "INSERT INTO game_design_published_realm_policy_set (" + + columnList + + ") SELECT " + + selectList + + " FROM game_design_published_realm_policy_set existing " + + "WHERE existing.canonical_tenant_id = ? AND existing.canonical_version_id = ?"; + } + + private static String publishedSetRowJson(Fixture fixture) { + var row = + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(s)::TEXT AS evidence FROM game_design_published_realm_policy_set s " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + assertThat(row).isNotNull(); + return row.get("evidence", String.class); + } + + private static List publishedPolicyRowsJson(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT to_jsonb(p)::TEXT AS evidence FROM game_design_published_realm_policy p " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? ORDER BY ordinal", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()) + .stream() + .map(row -> row.get("evidence", String.class)) + .toList(); + } + + private static Throwable rootCause(Throwable failure) { + Throwable cause = failure; + while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause(); + return cause; + } + + private static void assertPublishedSetUnchanged( + RealmPolicyPublishedEvidence.PublishedSet expected, + RealmPolicyPublishedEvidence.PublishedSet actual) { + assertThat(actual.target()).isEqualTo(expected.target()); + assertThat(actual.versionNumber()).isEqualTo(expected.versionNumber()); + assertThat(actual.sourceCommitId()).isEqualTo(expected.sourceCommitId()); + assertThat(actual.sourceEpoch()).isEqualTo(expected.sourceEpoch()); + assertThat(actual.publishedReleaseBundleRef()).isEqualTo(expected.publishedReleaseBundleRef()); + assertThat(actual.publishedReleaseBundleDigest()) + .isEqualTo(expected.publishedReleaseBundleDigest()); + assertThat(actual.publishWorkflowId()).isEqualTo(expected.publishWorkflowId()); + assertThat(actual.manifestHash()).isEqualTo(expected.manifestHash()); + assertThat(actual.publicationVersionStateEpoch()) + .isEqualTo(expected.publicationVersionStateEpoch()); + assertThat(actual.operationBytes()).containsExactly(expected.operationBytes()); + assertThat(actual.captureBytes()).containsExactly(expected.captureBytes()); + assertThat(actual.terminalEvidenceBytes()).containsExactly(expected.terminalEvidenceBytes()); + assertThat(actual.policyCount()).isEqualTo(expected.policyCount()); + assertThat(actual.policySetDigest()).isEqualTo(expected.policySetDigest()); + assertThat(actual.policies()).containsExactlyElementsOf(expected.policies()); + } + + private static PublishedReleaseBundle bundle(GameDesignPublicationOperation operation) + throws Exception { + var bundle = new PublishedReleaseBundle(); + bundle.setTenantId(operation.tenantKey()); + bundle.setVersionId(operation.versionId()); + bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(operation.account().tenantId()); + bundle.setCanonicalVersionId(operation.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(operation.workflowId()); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + bundle.setGenerationConfigRevision("generation-isolated-1"); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants( + operation.versionId(), operation.world()))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + DataSourceTransactionManager transactions, + TargetProof target, + DraftCommitBinding baseline, + VersionRepository versions, + PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, + GameDesignPublicationOperationRepository operations, + RealmPolicySourceRepository policySource, + RealmPolicyPublicationRepository publicationWrites, + RealmPolicyPublicationService publicationReads) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + + GameDesignPublicationOperation prepare(boolean capturePolicySource) throws Exception { + return tx( + () -> { + try { + var operation = IsolatedPublicationOwnerSetup.retain(dsl, target, 1); + if (capturePolicySource) { + policySource.captureSynchronized( + operation.account().input().selection().selectedCommit()); + policySource.freeze(operation); + } + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + void writePublish(GameDesignPublicationOperation operation, boolean rollBack) throws Exception { + write.executeWithoutResult( + status -> { + try { + IsolatedPublicationOwnerSetup.commitStorage( + dsl, versions, operation, () -> saveBundle(operation)); + if (rollBack) status.setRollbackOnly(); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + PublishedReleaseBundle saveBundle(GameDesignPublicationOperation operation) { + try { + return releases.save(bundle(operation)); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + void moveVersion(VersionLifecycleState next, long epoch) { + tx( + () -> { + var version = + versions + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + version.setVersionState(next); + version.setVersionStateEpoch(epoch); + versions.save(version); + return null; + }); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java new file mode 100644 index 0000000000..1ed06c63b4 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -0,0 +1,97 @@ +package unit.net.firedevops.firemud.gamedesign.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.util.List; +import net.firedevops.firemud.gamedesign.config.RealmPolicyPublicationReadConfiguration; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.io.FileSystemResource; +import org.springframework.transaction.PlatformTransactionManager; + +class RealmPolicyPublicationReadConfigurationTest { + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + RealmPolicyPublicationReadConfiguration.class, + RealmPolicyPublicationGrpcService.class) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withBean(PlatformTransactionManager.class, () -> mock(PlatformTransactionManager.class)); + + @Test + void ownerReadCompositionAndGrpcAdapterAreAbsentByDefault() { + contextRunner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationRepository.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationService.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationGrpcService.class); + }); + } + + @Test + void explicitEnablementComposesActualOwnerBeansAndGrpcAdapter() { + contextRunner + .withPropertyValues( + "firemud.game-design.published-realm-entry-policy-read.enabled=true", + "firemud.grpc.workload-namespace=firemud-test") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(RealmPolicyPublicationRepository.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationService.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationGrpcService.class); + }); + } + + @Test + void enabledCompositionFailsClosedForMissingOrInvalidNamespace() { + contextRunner + .withPropertyValues("firemud.game-design.published-realm-entry-policy-read.enabled=true") + .run(context -> assertThat(context).hasFailed()); + + contextRunner + .withPropertyValues( + "firemud.game-design.published-realm-entry-policy-read.enabled=true", + "firemud.grpc.workload-namespace=Invalid_Namespace") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void baseAndProductionYamlBindOnlyTheExplicitPolicyReadMethods() throws IOException { + assertConfiguredGrpcMethods("application.yml"); + assertConfiguredGrpcMethods("application-prod.yml"); + } + + private static void assertConfiguredGrpcMethods(String fileName) throws IOException { + var propertySources = + new YamlPropertySourceLoader() + .load(fileName, new FileSystemResource("src/main/resources/" + fileName)); + new ApplicationContextRunner() + .withInitializer( + context -> + propertySources.forEach(context.getEnvironment().getPropertySources()::addFirst)) + .run( + context -> + assertThat( + Binder.get(context.getEnvironment()) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())) + .containsExactly( + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation", + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource", + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", + "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies")); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java new file mode 100644 index 0000000000..3663aada47 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -0,0 +1,213 @@ +package unit.net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class AuthoredDraftPublishSelectionTest { + private static final String LARGE_COUNTER = "900719925474099312345678901234567890"; + + @Test + void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() throws Exception { + TargetProof target = target(); + DraftCommitBinding binding = binding(target); + VisibilityFence fence = + new VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[{\"appliedEpochs\":[{\"aggregateId\":\"world-17\"," + + "\"aggregateType\":\"WORLD_TEMPLATE\",\"expectedEpoch\":\"" + + LARGE_COUNTER + + "\",\"resultingEpoch\":\"900719925474099312345678901234567891\"," + + "\"scopeId\":\"room-scope-5\",\"scopeType\":\"ROOM_SCOPE\"}]," + + "\"bindingDigest\":\"" + + binding.digest() + + "\",\"commitId\":\"" + + binding.commitId() + + "\",\"owner\":\"WORLD_MANAGEMENT\",\"resultBytesBase64\":\"YXBwbGllZA==\"," + + "\"resultIdentity\":\"world-result-1\",\"status\":\"APPLIED\"}]", + OffsetDateTime.parse("2026-10-05T00:00:00Z")); + PublishIntent intent = + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-request-é", + LARGE_COUNTER, + "Exact creator notes — preserve spacing ", + binding.requestId(), + binding.commitId(), + binding.digest()); + + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + AuthoredDraftPublishSelection restored = + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()); + + assertThat(restored).isEqualTo(selection); + assertThat(restored.intent().notes()).isEqualTo(intent.notes()); + assertThat(restored.intent().expectedVersionStateEpoch()).isEqualTo(LARGE_COUNTER); + assertThat(restored.canonicalJson()) + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedVersionStateEpoch\":\"" + LARGE_COUNTER + "\""); + assertThat(restored.selectedCommit().canonicalJson()).isEqualTo(binding.canonicalJson()); + assertThat(restored.fenceResultVectorJson()).isEqualTo(fence.resultVectorJson()); + assertThat(restored.fenceCreatedAt()).isEqualTo("2026-10-05T00:00:00Z"); + // Independent original V43 object layout. Extraction must preserve its exact bytes/digest. + byte[] legacy = + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + Map.of( + "schemaVersion", + "1", + "intent", + Map.of( + "canonicalTenantId", + intent.canonicalTenantId().toString(), + "canonicalVersionId", + intent.canonicalVersionId().toString(), + "publishRequestId", + intent.publishRequestId(), + "expectedVersionStateEpoch", + intent.expectedVersionStateEpoch(), + "notes", + intent.notes(), + "selectedCommitRequestId", + intent.selectedCommitRequestId().toString(), + "selectedCommitId", + intent.selectedCommitId().toString(), + "selectedCommitDigest", + intent.selectedCommitDigest()), + "target", + Map.of( + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind()), + "selectedCommitBindingJson", + binding.canonicalJson(), + "selectedCommitDigest", + binding.digest(), + "synchronizedFence", + Map.of( + "requestId", + fence.requestId().toString(), + "commitId", + fence.commitId().toString(), + "inputDigest", + fence.inputDigest(), + "resultVectorJson", + fence.resultVectorJson(), + "createdAt", + "2026-10-05T00:00:00Z")))); + assertThat(selection.canonicalBytes()).containsExactly(legacy); + assertThat(selection.digest()).isEqualTo(DraftAuthorizationFenceBinding.digest(legacy)); + var shared = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + assertThat(shared.canonicalBytes()).containsExactly(legacy); + } + + @Test + void rejectsInvalidSelectionEpochAndChangedIntent() { + TargetProof target = target(); + DraftCommitBinding binding = binding(target); + PublishIntent original = intent(target, binding, "original notes"); + + assertThatThrownBy( + () -> + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + original.publishRequestId(), + "01", + original.notes(), + binding.requestId(), + binding.commitId(), + binding.digest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive canonical decimal"); + assertThat(original).isNotEqualTo(intent(target, binding, "changed notes")); + } + + private static TargetProof target() { + return new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"); + } + + private static DraftCommitBinding binding(TargetProof target) { + return DraftCommitBinding.create( + target, + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-exact-9", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\"fullTypedMutation\":{\"unknown\":\"retained\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-17", + "ROOM_SCOPE", + "room-scope-5", + LARGE_COUNTER))); + } + + private static PublishIntent intent( + TargetProof target, DraftCommitBinding binding, String notes) { + return new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-request-7", + LARGE_COUNTER, + notes, + binding.requestId(), + binding.commitId(), + binding.digest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java new file mode 100644 index 0000000000..78b7d4afa8 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +import org.junit.jupiter.api.Test; + +class GameDesignReviewedBaseEvidenceTest { + @Test + void genesisBindsOriginalPairedReceiptTargetAndCreationWitnessWithoutCommit() { + var target = + new TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 7, "tenant", 3, "tenant", "NEW_GAME_ROW"); + var receipt = UUID.randomUUID(); + var genesis = genesis(target, receipt, "11"); + var evidence = GameDesignReviewedBaseEvidence.genesis(genesis); + assertThat(evidence.target()).isEqualTo(target); + assertThat(evidence.reference()).isEqualTo(DraftBaseReference.parse("genesis:" + receipt)); + assertThat(evidence.canonicalBytes()).contains(genesis.policy().canonicalBytes()); + assertThat(evidence.canonicalBytes()).contains(genesis.command().canonicalBytes()); + assertThat(evidence.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(evidence.canonicalBytes())); + assertThat(evidence).isEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis)); + assertThat(evidence) + .isNotEqualTo(GameDesignReviewedBaseEvidence.genesis(genesis(target, receipt, "12"))); + assertThat(evidence) + .isNotEqualTo( + GameDesignReviewedBaseEvidence.genesis(genesis(target, UUID.randomUUID(), "11"))); + byte[] returned = evidence.canonicalBytes(); + returned[0] ^= 1; + assertThat(returned).isNotEqualTo(evidence.canonicalBytes()); + } + + @Test + void readbackRejectsChangedDigestAndDefensivelyCopiesBytes() { + byte[] bytes = {1, 2, 3}; + var retained = + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + bytes, DraftAuthorizationFenceBinding.digest(bytes)); + bytes[0] = 9; + assertThat(retained.canonicalBytes()).containsExactly(1, 2, 3); + assertThatThrownBy( + () -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback(bytes, retained.digest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static GameDesignSourceRepository.Genesis genesis( + TargetProof target, UUID receipt, String witness) { + return new GameDesignSourceRepository.Genesis( + new RealmPolicyGenesis(target, receipt, witness), + new CommandSource.NewDraftGenesisReceipt(target, receipt, witness)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java new file mode 100644 index 0000000000..c645b1dd4f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -0,0 +1,261 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.publication.CommandApplication; +import net.firedevops.firemud.gamedesign.publication.CommandSnapshot; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import org.junit.jupiter.api.Test; + +class CommandSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 7L, "owner", 3L, "owner", "NEW_GAME_ROW"); + + @Test + void parsesOnlyClosedDigestBoundOperationsAndRetainsExactPayloadAndProvenance() { + String definition = + command("look", "l").replace("{\"schemaVersion\":1", "{ \"schemaVersion\":1"); + UUID commitId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + var binding = + binding( + commitId, + List.of(revision("0", revisionId, CommandSource.upsertPayload(definition))), + List.of(commandScope("0"))); + + var mutation = CommandSource.mutations(binding).getFirst(); + assertThat(mutation.commandId()).isEqualTo("look"); + assertThat(mutation.definitionJson()).isEqualTo(definition); + assertThat(mutation.commitId()).isEqualTo(commitId); + assertThat(mutation.revisionId()).isEqualTo(revisionId); + assertThat(mutation.revisionOrder()).isEqualTo("0"); + + var malformed = + List.of( + CommandSource.upsertPayload(definition) + .replace("\"operation\":\"UPSERT\"", "\"operation\":\"UPSERT\",\"extra\":true"), + "{\"schemaVersion\":1,\"revisionKind\":\"UNSUPPORTED\",\"operation\":\"DELETE\",\"commandId\":\"look\"}", + CommandSource.upsertPayload(definition) + .replace("\"schemaVersion\":1", "\"schemaVersion\":2")); + for (String payload : malformed) { + var bad = + binding( + commitId, List.of(revision("0", revisionId, payload)), List.of(commandScope("0"))); + assertThatThrownBy(() -> CommandSource.mutations(bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void replaysStableKeyUpsertAndExplicitDeleteInRevisionOrderWithoutLosingAuthorship() { + var inherited = List.of(definition("look", "l", UUID.randomUUID(), UUID.randomUUID(), "0")); + UUID commit = UUID.randomUUID(); + UUID upsertRevision = UUID.randomUUID(); + String exactDefinition = command("LOOK", "see"); + var operations = + List.of( + new CommandSource.Mutation( + "0", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "look", null), + new CommandSource.Mutation( + "1", + upsertRevision, + commit, + CommandSource.OperationKind.UPSERT, + "LOOK", + exactDefinition), + new CommandSource.Mutation( + "2", + UUID.randomUUID(), + commit, + CommandSource.OperationKind.DELETE, + "absent", + null)); + + var result = CommandSource.replay(inherited, operations); + assertThat(result).hasSize(1); + assertThat(result.getFirst().commandId()).isEqualTo("LOOK"); + assertThat(result.getFirst().definitionJson()).isEqualTo(exactDefinition); + assertThat(result.getFirst().sourceCommitId()).isEqualTo(commit); + assertThat(result.getFirst().sourceRevisionId()).isEqualTo(upsertRevision); + assertThat(CommandSource.replay(inherited, List.of())).containsExactlyElementsOf(inherited); + assertThat(CommandSource.replay(result, List.of(operations.get(2)))) + .containsExactlyElementsOf(result); + assertThatThrownBy( + () -> CommandSource.replay(inherited, List.of(operations.get(1), operations.get(0)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void mixedControlPlaneCommitReturnsCommandEvidenceWithoutTakingOwnerOutcomeOwnership() { + UUID commitId = UUID.randomUUID(); + var commandRevision = + revision("0", UUID.randomUUID(), CommandSource.upsertPayload(command("look", "l"))); + var policyRevision = + revision( + "1", + UUID.randomUUID(), + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"main\",\"policy\":{}}"); + var policyScope = + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + TARGET.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"); + var binding = + binding( + commitId, + List.of(commandRevision, policyRevision), + List.of(commandScope("0"), policyScope)); + + var mutations = CommandSource.mutations(binding); + assertThat(mutations).hasSize(1); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isTrue(); + var snapshot = + new CommandSnapshot( + binding, + "1", + null, + "sha256:" + "b".repeat(64), + CommandSource.replay(List.of(), mutations)); + var evidence = new CommandApplication(binding, null, "0", mutations, snapshot); + assertThat(evidence.commandAppliedEpoch()) + .isEqualTo( + new DraftCommitCoordinatorRepository.AppliedEpoch( + CommandSource.SCOPE, + TARGET.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + "0", + "1")); + byte[] applicationBytes = evidence.canonicalBytes(); + byte[] schemaBytes = CommandSource.APPLICATION_SCHEMA.getBytes(StandardCharsets.UTF_8); + assertThat(applicationBytes).isNotEmpty(); + assertThat(ByteBuffer.wrap(applicationBytes).getInt()).isEqualTo(schemaBytes.length); + assertThat(ByteBuffer.wrap(applicationBytes).getInt(4 + schemaBytes.length)).isZero(); + } + + @Test + void rejectsAmbiguousAliasesAndKeepsTheEntireEffectiveSet() { + var first = definition("look", "inspect", UUID.randomUUID(), UUID.randomUUID(), "0"); + var collision = definition("inspect", "peek", UUID.randomUUID(), UUID.randomUUID(), "1"); + assertThatThrownBy(() -> CommandSource.replay(List.of(first, collision), List.of())) + .isInstanceOf(IllegalArgumentException.class); + + List inherited = new ArrayList<>(); + for (int index = 0; index < 140; index++) { + inherited.add( + definition( + "command-" + index, "alias-" + index, UUID.randomUUID(), UUID.randomUUID(), "0")); + } + assertThat(CommandSource.replay(inherited, List.of())).hasSize(140); + } + + @Test + void snapshotRoundTripAndCaptureBindTheActualSelectedCommit() throws Exception { + GameDesignPublicationOperation operation = IsolatedPublicationOperationFixtures.fresh(TARGET); + var selected = operation.account().input().selection().selectedCommit(); + var snapshot = new CommandSnapshot(selected, "0", null, "sha256:" + "a".repeat(64), List.of()); + String canonicalJson = snapshot.canonicalJson(); + assertThat(CommandSnapshot.fromStored(canonicalJson)).isEqualTo(snapshot); + assertThat(canonicalJson).contains("\"inheritedCommitId\":\"\""); + List invalidInheritedCommitIds = + List.of( + canonicalJson.replace(",\"inheritedCommitId\":\"\"", ""), + canonicalJson.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":null"), + canonicalJson.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":7"), + canonicalJson.replace( + "\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":\"not-a-uuid\"")); + for (String invalidJson : invalidInheritedCommitIds) { + assertThatThrownBy(() -> CommandSnapshot.fromStored(invalidJson)) + .isInstanceOf(IllegalArgumentException.class); + } + var capture = new CommandSnapshot.Capture(operation, snapshot); + assertThat(new String(capture.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains("game-design-command-source-capture/v1"); + + var wrongCommit = + DraftCommitBinding.create( + selected.target(), + UUID.randomUUID(), + UUID.randomUUID(), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + assertThatThrownBy( + () -> + new CommandSnapshot.Capture( + operation, + new CommandSnapshot( + wrongCommit, "0", null, "sha256:" + "a".repeat(64), List.of()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void freshGenesisReceiptRequiresExactVersionInsertTransactionIdentity() { + var receipt = new CommandSource.NewDraftGenesisReceipt(TARGET, UUID.randomUUID(), "1234567"); + assertThat(receipt.digest()).startsWith("sha256:"); + assertThat(new String(receipt.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains("1234567"); + assertThatThrownBy( + () -> new CommandSource.NewDraftGenesisReceipt(TARGET, UUID.randomUUID(), "0")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CommandSource.Definition definition( + String commandId, String alias, UUID commitId, UUID revisionId, String revisionOrder) { + return new CommandSource.Definition( + commandId, command(commandId, alias), commitId, revisionId, revisionOrder); + } + + private static String command(String id, String alias) { + return "{\"schemaVersion\":1,\"commandId\":\"" + + id + + "\",\"semanticOwner\":\"WORLD\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"" + + alias + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," + + "\"legacyExtension\":{\"kept\":true}}"; + } + + private static DraftCommitBinding.RevisionPayload revision( + String order, UUID id, String payload) { + return new DraftCommitBinding.RevisionPayload( + order, id, Owner.GAME_DESIGN_CONTROL_PLANE, payload); + } + + private static DraftCommitBinding.AffectedUnit commandScope(String epoch) { + return new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + TARGET.canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + epoch); + } + + private static DraftCommitBinding binding( + UUID commitId, + List revisions, + List units) { + return DraftCommitBinding.create( + TARGET, UUID.randomUUID(), commitId, "ISOLATED-exact-base", revisions, units); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java new file mode 100644 index 0000000000..f01ca0b6f0 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.junit.jupiter.api.Test; + +class RealmPolicyApplicationTest { + @Test + void genesisApplicationFramesAbsentInheritedCommitAsEmptyBytesAndBindsOwnerOutcome() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 17L, + "tenant-key", + 23L, + "tenant-key", + "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis:" + UUID.randomUUID(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "world-revision")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM", + "room", + "0"))); + var genesis = new RealmPolicyGenesis(target, UUID.randomUUID(), "1"); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of()); + var application = new RealmPolicyApplication(genesis, null, "0", snapshot); + + ByteArrayOutputStream expected = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(expected, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(expected, "true"); + DraftAuthorizationFenceBinding.frame(expected, genesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(expected, "false"); + DraftAuthorizationFenceBinding.frame(expected, new byte[0]); + DraftAuthorizationFenceBinding.frame(expected, "0"); + DraftAuthorizationFenceBinding.frame(expected, snapshot.canonicalBytes()); + + var ownerOutcome = application.ownerOutcome(); + assertThat(application.canonicalBytes()).containsExactly(expected.toByteArray()); + assertThat(ownerOutcome) + .isEqualTo( + new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "realm-policy:" + binding.commitId(), + expected.toByteArray(), + List.of( + new AppliedEpoch( + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + "1")))); + + UUID inheritedCommitId = UUID.randomUUID(); + var inherited = new RealmPolicyApplication(inheritedCommitId, "0", snapshot); + ByteArrayOutputStream expectedInherited = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + expectedInherited, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(expectedInherited, "false"); + DraftAuthorizationFenceBinding.frame(expectedInherited, new byte[0]); + DraftAuthorizationFenceBinding.frame(expectedInherited, "true"); + DraftAuthorizationFenceBinding.frame(expectedInherited, inheritedCommitId.toString()); + DraftAuthorizationFenceBinding.frame(expectedInherited, "0"); + DraftAuthorizationFenceBinding.frame(expectedInherited, snapshot.canonicalBytes()); + + assertThat(inherited.canonicalBytes()).containsExactly(expectedInherited.toByteArray()); + assertThat(inherited.canonicalBytes()).isNotEqualTo(application.canonicalBytes()); + assertThat(inherited.ownerOutcome().resultBytes()) + .containsExactly(expectedInherited.toByteArray()); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java new file mode 100644 index 0000000000..b4f70e077b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java @@ -0,0 +1,420 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.io.ByteArrayOutputStream; +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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +/** + * Adapter tests use isolated owner evidence and context identities, not DB or physical mTLS proof. + */ +class RealmPolicyPublicationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void rejectsAbsentWrongNamespaceAndEndUserPeersBeforeDecodeOrOwnerAccess() { + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var malformed = ListPublishedRealmEntryPoliciesRequest.getDefaultInstance(); + + assertThat(callList(handler, malformed, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(callList(handler, malformed, peer("account-service", NAMESPACE)).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(callList(handler, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + try { + assertThat(callList(handler, malformed, peer("game-session-service", NAMESPACE)).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void malformedAndWrongRequestNamespacesAreDeniedBeforeOwnerAccess() { + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var peer = peer("game-session-service", NAMESPACE); + var malformed = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .build(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var unknownRequest = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId("99999999-9999-4999-8999-999999999999") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .setUnknownFields(unknown) + .build(); + var wrongNamespace = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("other") + .setReadRequestId("99999999-9999-4999-8999-999999999999") + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .build(); + + assertThat(callList(handler, malformed, peer).error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callList(handler, unknownRequest, peer).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callList(handler, wrongNamespace, peer).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void readsAndReturnsTheCompleteSetAndDoesNotFallBackForAnAbsentSelector() throws Exception { + var fixture = publishedSet(); + var owner = mock(RealmPolicyPublicationService.class); + when(owner.readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId())) + .thenReturn(Optional.of(fixture.set())); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + var peer = peer("game-session-service", NAMESPACE); + + var listRequest = listRequest(fixture); + var listedWire = + callList(handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest), peer); + assertThat(listedWire.error).isNull(); + var listed = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listedWire.response); + assertThat(listed.target()).isEqualTo(fixture.target()); + assertThat(listed.policyCount()).isEqualTo(1); + assertThat(listed.policies()).hasSize(1); + assertThat(listed.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(listed.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(listed.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(listed.terminalEvidenceBytes()).isEqualTo(fixture.set().terminalEvidenceBytes()); + + var resolveRequest = resolveRequest(fixture, "main"); + var resolvedWire = + callResolve( + handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest), peer); + assertThat(resolvedWire.error).isNull(); + var resolved = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolvedWire.response); + assertThat(resolved).isEqualTo(listed); + + var missingSelector = resolveRequest(fixture, "absent"); + var missing = + callResolve( + handler, PublishedRealmEntryPolicyReadGrpcCodec.toRequest(missingSelector), peer); + assertThat(missing.error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.response).isNull(); + verify(owner, org.mockito.Mockito.times(3)) + .readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()); + } + + @Test + void absentOwnerEvidenceUnavailableStorageAndContradictoryEvidenceHaveDistinctStatuses() + throws Exception { + var fixture = publishedSet(); + var request = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest(fixture)); + var peer = peer("game-session-service", NAMESPACE); + var owner = mock(RealmPolicyPublicationService.class); + var handler = new RealmPolicyPublicationGrpcService(owner, NAMESPACE); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))).thenReturn(Optional.empty()); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.NOT_FOUND); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow(new org.jooq.exception.DataAccessException("ISOLATED storage unavailable")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow(new IllegalStateException("ISOLATED contradictory owner evidence")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest(Fixture fixture) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + NAMESPACE, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + } + + static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequest( + Fixture fixture, String realmSlug) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + NAMESPACE, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + "earth", + realmSlug); + } + + static Fixture publishedSet() throws Exception { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42L, + "tenant-key", + 7L, + "tenant-key", + "NEW_GAME_ROW"); + GameDesignPublicationOperation operation = IsolatedPublicationOperationFixtures.fresh(target); + var selection = operation.account().input().selection(); + var source = + new RealmPolicySource.Policy( + selection.selectedCommit().commitId(), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "main-policy-v1", + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON)); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release(operation), 6L); + byte[] capture = capture(operation, source, "43"); + String policyDigest = + RealmPolicyPublishedEvidence.policyDigest( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + source); + var policy = + new RealmPolicyPublishedEvidence.Policy( + UUID.fromString("44444444-4444-4444-8444-444444444444"), source, policyDigest); + var policies = List.of(policy); + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + terminal.releaseContent().versionNumber(), + selection.selectedCommit().commitId(), + "43", + terminal.releaseContent().publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + var ownerSet = + new RealmPolicyPublishedEvidence.PublishedSet( + target, + terminal.releaseContent().versionNumber(), + selection.selectedCommit().commitId(), + "43", + terminal.releaseContent().publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + 1, + setDigest, + policies); + return new Fixture(target, ownerSet); + } + + private static byte[] capture( + GameDesignPublicationOperation operation, RealmPolicySource.Policy source, String epoch) + throws IOException { + var policy = JSON.readTree(source.policy().canonicalJson()); + var snapshot = + Map.of( + "schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", operation.account().input().selection().selectedCommit().canonicalJson(), + "bindingDigest", operation.account().input().selection().selectedCommit().digest(), + "sourceEpoch", epoch, + "policies", + List.of( + Map.of( + "commitId", source.commitId().toString(), + "revisionId", source.revisionId().toString(), + "logicalRevisionId", source.logicalRevisionId(), + "policy", policy))); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } + + private static ReleaseContent release(GameDesignPublicationOperation operation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + List.of("LOOK"), + "generation-1", + operation.world()); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static ListCollector callList( + RealmPolicyPublicationGrpcService handler, + ListPublishedRealmEntryPoliciesRequest request, + GrpcPeerIdentity peer) { + var observer = new ListCollector(); + withPeer(peer, () -> handler.listPublishedRealmEntryPolicies(request, observer)); + return observer; + } + + private static ResolveCollector callResolve( + RealmPolicyPublicationGrpcService handler, + ResolvePublishedRealmEntryPolicyRequest request, + GrpcPeerIdentity peer) { + var observer = new ResolveCollector(); + withPeer(peer, () -> handler.resolvePublishedRealmEntryPolicy(request, observer)); + return observer; + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + record Fixture( + DraftCommitBinding.TargetProof target, RealmPolicyPublishedEvidence.PublishedSet set) {} + + private static final class ListCollector + implements StreamObserver { + private ListPublishedRealmEntryPoliciesResponse response; + private Status.Code error; + + @Override + public void onNext(ListPublishedRealmEntryPoliciesResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class ResolveCollector + implements StreamObserver { + private ResolvePublishedRealmEntryPolicyResponse response; + private Status.Code error; + + @Override + public void onNext(ResolvePublishedRealmEntryPolicyResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java new file mode 100644 index 0000000000..6ebe197e69 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java @@ -0,0 +1,345 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +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.when; + +import io.grpc.ManagedChannel; +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.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Loopback transport proof for the production handler/interceptor; owner data stays isolated. */ +class RealmPolicyPublicationMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SERVER_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + var pair = newRsaKeyPair(); + var name = new X500Name("CN=Realm Policy Test CA, O=FireMUD Test"); + var ca = issueCertificate(name, pair.getPublic(), name, pair.getPrivate(), true); + pki = + new TestPki( + ca, + issueLeaf(name, pair.getPrivate(), "game-design-server", SERVER_URI), + issueLeaf( + name, + pair.getPrivate(), + "game-session-client", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-service-client", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-namespace-client", + "spiffe://firemud/ns/other/sa/game-session-service")); + } + + @Test + void trustedWrongServiceAndNamespaceDenyBeforeMalformedDecodeOrOwnerRead() throws Exception { + var owner = mock(RealmPolicyPublicationService.class); + var server = server(owner); + try { + for (var identity : List.of(pki.wrongService(), pki.wrongNamespace())) { + var channel = channel(server, identity); + try { + assertThat( + listFailure(channel, ListPublishedRealmEntryPoliciesRequest.getDefaultInstance())) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + close(channel); + } + } + verifyNoInteractions(owner); + } finally { + stopServer(server); + } + } + + @Test + void exactGameSessionPeerReadsTheFullSetAndResolvesOnlyItsExactSelector() throws Exception { + var fixture = RealmPolicyPublicationGrpcServiceTest.publishedSet(); + var owner = mock(RealmPolicyPublicationService.class); + when(owner.readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId())) + .thenReturn(Optional.of(fixture.set())); + var server = server(owner); + try { + var channel = channel(server, pki.gameSession()); + try { + var listRequest = RealmPolicyPublicationGrpcServiceTest.listRequest(fixture); + var listed = + stub(channel) + .listPublishedRealmEntryPolicies( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest)); + var complete = PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listed); + assertThat(complete.policyCount()).isEqualTo(fixture.set().policyCount()); + assertThat(complete.policies()).hasSize(fixture.set().policyCount()); + assertThat(complete.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(complete.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(complete.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(complete.terminalEvidenceBytes()) + .isEqualTo(fixture.set().terminalEvidenceBytes()); + + var resolveRequest = RealmPolicyPublicationGrpcServiceTest.resolveRequest(fixture, "main"); + var resolved = + stub(channel) + .resolvePublishedRealmEntryPolicy( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest)); + var selected = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolved); + assertThat(selected).isEqualTo(complete); + assertThat(selected.policies()) + .anySatisfy( + policy -> { + assertThat(policy.policy().worldSlug()).isEqualTo("earth"); + assertThat(policy.policy().realmSlug()).isEqualTo("main"); + }); + verify(owner, times(2)) + .readPublishedSet( + fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()); + } finally { + close(channel); + } + } finally { + stopServer(server); + } + } + + @Test + void exactPeerRejectsMalformedAndMismatchedNamespaceBeforeOwnerRead() throws Exception { + var owner = mock(RealmPolicyPublicationService.class); + var server = server(owner); + try { + var channel = channel(server, pki.gameSession()); + try { + assertThat( + listFailure(channel, ListPublishedRealmEntryPoliciesRequest.getDefaultInstance())) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var fixture = RealmPolicyPublicationGrpcServiceTest.publishedSet(); + var mismatchedNamespace = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + RealmPolicyPublicationGrpcServiceTest.listRequest(fixture)) + .toBuilder() + .setTargetNamespace("other") + .build(); + assertThat(listFailure(channel, mismatchedNamespace)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + close(channel); + } + verifyNoInteractions(owner); + } finally { + stopServer(server); + } + } + + private static Server server(RealmPolicyPublicationService owner) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.server().privateKey(), pki.server().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new RealmPolicyPublicationGrpcService(owner, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), + Set.of( + PublishedRealmEntryPolicyServiceGrpc + .getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc + .getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName())))) + .build() + .start(); + } + + private static ManagedChannel channel(Server server, TestCertificate identity) throws Exception { + return NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate()) + .build()) + .build(); + } + + private static PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + stub(ManagedChannel channel) { + return PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(SERVER_URI)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(SERVER_URI)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } + + private static Status.Code listFailure( + ManagedChannel channel, ListPublishedRealmEntryPoliciesRequest request) { + try { + stub(channel).listPublishedRealmEntryPolicies(request); + return null; + } catch (StatusRuntimeException failure) { + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isFalse(); + return Status.fromThrowable(failure).getCode(); + } + } + + private static void close(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca) + throws Exception { + return issueCertificate(subject, publicKey, issuer, issuerPrivateKey, ca, null); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate server, + TestCertificate gameSession, + TestCertificate wrongService, + TestCertificate wrongNamespace) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java new file mode 100644 index 0000000000..3356b62a48 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceTest.java @@ -0,0 +1,227 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class RealmPolicyPublishedEvidenceTest { + @Test + void policyDigestMatchesIndependentCanonicalKnownVector() { + var target = + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42, + "tenant-42", + 7, + "tenant-42", + "NEW_GAME_ROW"); + var source = + new RealmPolicySource.Policy( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "main-policy-v1", + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper())); + UUID policyId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + source); + + assertThat(digest) + .isEqualTo("sha256:1cb51d94ec2825d1d598fa30c197e6ce52d23b8a62106b04babcaafc92be2f47"); + var changedPolicy = + new RealmPolicySource.Policy( + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Changed\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper())); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + changedPolicy)) + .isNotEqualTo(digest); + } + + @Test + void targetProofUsesCompleteStableIdentityAndExactDecimalRowIds() { + var target = target(); + String encoded = RealmPolicyPublishedEvidence.targetProofJson(target); + var decoded = new ObjectMapper().readTree(encoded); + + assertThat(decoded.size()).isEqualTo(7); + assertThat(decoded.path("canonicalTenantId").asText()) + .isEqualTo(target.canonicalTenantId().toString()); + assertThat(decoded.path("canonicalVersionId").asText()) + .isEqualTo(target.canonicalVersionId().toString()); + assertThat(decoded.path("gameDesignVersionRowId").asText()) + .isEqualTo(Long.toString(target.gameDesignVersionRowId())); + assertThat(decoded.path("sourceGameRowId").asText()) + .isEqualTo(Long.toString(target.sourceGameRowId())); + assertThat(RealmPolicyPublishedEvidence.targetProofJson(target)) + .isEqualTo(RealmPolicyPublishedEvidence.targetProofJson(target)); + } + + @Test + void policyAndCompleteSetDigestsBindOriginalSourceAndActualReleaseEvidence() { + var target = target(); + var main = source("main", true, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + var privateRealm = + source("private", false, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + UUID policyId = UUID.randomUUID(); + String bundleRef = "actual-owner-bundle-reference"; + String bundleDigest = digest('a'); + String workflow = "publish-workflow-original"; + String manifest = digest('b'); + + String originalPolicyDigest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, main); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, main)) + .isEqualTo(originalPolicyDigest); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, "different-bundle", bundleDigest, workflow, manifest, main)) + .isNotEqualTo(originalPolicyDigest); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, digest('c'), workflow, manifest, main)) + .isNotEqualTo(originalPolicyDigest); + var changedRevision = + source("main", true, main.commitId(), UUID.randomUUID(), UUID.randomUUID()); + assertThat( + RealmPolicyPublishedEvidence.policyDigest( + policyId, target, 12, bundleRef, bundleDigest, workflow, manifest, changedRevision)) + .isNotEqualTo(originalPolicyDigest); + + // Use stable row identities so the set comparison covers only the requested byte change. + var secondId = UUID.randomUUID(); + var rows = + List.of( + new RealmPolicyPublishedEvidence.Policy(policyId, main, originalPolicyDigest), + new RealmPolicyPublishedEvidence.Policy( + secondId, + privateRealm, + RealmPolicyPublishedEvidence.policyDigest( + secondId, + target, + 12, + bundleRef, + bundleDigest, + workflow, + manifest, + privateRealm))); + String originalSet = + setDigest(target, main, bundleRef, bundleDigest, workflow, manifest, rows, new byte[] {1}); + assertThat( + setDigest( + target, + main, + bundleRef, + bundleDigest, + workflow, + manifest, + List.of(rows.get(1), rows.get(0)), + new byte[] {1})) + .isEqualTo(originalSet); + assertThat( + setDigest( + target, main, bundleRef, bundleDigest, workflow, manifest, rows, new byte[] {2})) + .isNotEqualTo(originalSet); + assertThat( + setDigest( + target, main, bundleRef, digest('c'), workflow, manifest, rows, new byte[] {1})) + .isNotEqualTo(originalSet); + } + + private String setDigest( + TargetProof target, + RealmPolicySource.Policy main, + String bundleRef, + String bundleDigest, + String workflow, + String manifest, + List rows, + byte[] terminal) { + return RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + 12, + main.commitId(), + "43", + bundleRef, + bundleDigest, + workflow, + manifest, + 19, + new byte[] {3}, + new byte[] {4}, + terminal, + rows); + } + + private static RealmPolicySource.Policy source( + String realm, + boolean production, + UUID commitId, + UUID revisionId, + UUID logicalRevisionSuffix) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + return new RealmPolicySource.Policy( + commitId, revisionId, "source-" + logicalRevisionSuffix, policy); + } + + private static TargetProof target() { + return new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + Long.MAX_VALUE - 3, + "ISOLATED-tenant", + Long.MAX_VALUE - 7, + "ISOLATED-tenant", + "NEW_GAME_ROW"); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java new file mode 100644 index 0000000000..bc6a4e3232 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class RealmPolicySourceTest { + @Test + void draftPolicyStateCanBeEmptyOrIncompleteWithoutPublicationCardinality() { + var empty = new RealmPolicySnapshot(binding(), "0", List.of()); + assertThat(RealmPolicySnapshot.fromStored(empty.canonicalJson()).policies()).isEmpty(); + var hidden = policy("private", false); + assertThat(RealmPolicySource.effective(List.of(), List.of(hidden))).containsExactly(hidden); + assertThatThrownBy(() -> RealmPolicySource.ordered(empty.policies())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(hidden))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactCanonicalSnapshotRetainsOriginalAuthoredProvenanceAndDisjointInheritance() { + var original = policy("main", true); + var binding = binding(); + var snapshot = + new RealmPolicySnapshot(binding, "90071992547409931234567890", List.of(original)); + assertThat(RealmPolicySnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(RealmPolicySource.effective(snapshot.policies(), List.of())) + .containsExactly(original); + assertThatThrownBy(() -> RealmPolicySnapshot.fromStored(snapshot.canonicalJson() + " ")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void closedTypedRevisionRejectsMalformedUnknownAndUnsupportedFields() { + var binding = binding(); + var original = policy("main", true); + String payload = + "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"authored-main\",\"policy\":" + + original.policy().canonicalJson() + + "}"; + var input = + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload); + assertThat(RealmPolicySource.revision(binding, input).logicalRevisionId()) + .isEqualTo("authored-main"); + for (String malformed : + List.of( + payload.replace("PRESEEDED_ONLY", "AUTO_PROVISIONED"), + payload.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"extra\":true"), + payload.replace( + "\"revisionKind\":", + "\"revisionKind\":\"REALM_ENTRY_POLICY\",\"revisionKind\":"))) { + assertThatThrownBy( + () -> + RealmPolicySource.revision( + binding, + new DraftCommitBinding.RevisionPayload( + "0", input.revisionId(), input.owner(), malformed))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void effectiveSetRejectsDuplicateRealmAndProductionAndOverLimitInsteadOfTruncating() { + var main = policy("main", true); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(main, policy("main", false)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(main, policy("another", true)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RealmPolicySource.ordered(List.of(policy("hidden", false)))) + .isInstanceOf(IllegalArgumentException.class); + var bound = IntStream.range(0, 128).mapToObj(i -> policy("realm-" + i, i == 0)).toList(); + assertThat(RealmPolicySource.ordered(bound)).hasSize(128); + var oversized = new java.util.ArrayList<>(bound); + oversized.add(policy("last", false)); + assertThatThrownBy(() -> RealmPolicySource.ordered(oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RealmPolicySource.Policy policy(String realm, boolean production) { + String json = + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return new RealmPolicySource.Policy( + UUID.randomUUID(), + UUID.randomUUID(), + "authored-" + realm, + RealmEntryPolicy.parse(json, new ObjectMapper())); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "owner", 1, "owner", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "ISOLATED-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ISOLATED-world")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, "ROOM", "room", "ROOM", "room", "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..750a243e20 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class LaunchDescriptorRepositoryTest { + @Test + void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws Exception { + UUID canonicalTenantId = UUID.fromString("09cb7579-69b0-492b-82eb-7bb2231c0211"); + UUID sourceOperationId = UUID.fromString("c4651f34-8cb8-4ef8-b6f5-4aa19f8c1c42"); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 3, 10, 15, 30, 123_000_000); + + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:launch-descriptor-readback;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE launch_descriptor (" + + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision TEXT, " + + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, world_slug VARCHAR(120), " + + "authored_world_source_operation_id UUID, " + + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " + + "failure_code VARCHAR(64), failure_message VARCHAR(1000), created_at TIMESTAMP)"); + dsl.execute( + "INSERT INTO launch_descriptor (id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, world_slug, " + + "authored_world_source_operation_id, authored_world_source_evidence_digest, " + + "request_digest, result_digest, original_request_json, source_evidence_json, " + + "outcome_status, failure_code, failure_message, created_at) VALUES " + + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " + + "'patch-4', '{}', '" + + "generation-6:" + + "g".repeat(180) + + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + + canonicalTenantId + + "', 'verdant-harbor', '" + + sourceOperationId + + "', 'sha256:source', 'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); + + var descriptor = + new LaunchDescriptorRepository(dsl) + .findBoundByRequest("preview", canonicalTenantId, "request-17") + .orElseThrow(); + + assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getGenerationConfigRevision()) + .isEqualTo("generation-6:" + "g".repeat(180)); + assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java new file mode 100644 index 0000000000..755f6ce80a --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -0,0 +1,291 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedReleaseBundleRepositoryTest { + private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + + @Test + void selectorEvidenceRequiresExactSourceAndReadbackPreservesOriginalBytes() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + var evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + TENANT_UUID, VERSION_UUID, 17L, "tenant-key", 7L, "tenant-key", "NEW_GAME_ROW")); + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + requested.setAttestationSchemaVersion("v2"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mandatory"); + requested.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + requested.setPublishWorkflowId("other-workflow"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source/workflow"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + requested.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString(PublishedWorldSelectorFixtures.participants(17L, evidence))); + var saved = fixture.repository().save(requested); + assertThat(saved.getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(requested.getWorldPublishedStartLocationEvidenceJson()); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId("tenant-key", 17L) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + assertThat(fixture.repository().save(requested)).usingRecursiveComparison().isEqualTo(saved); + requested.setParticipantDigestsJson("[]"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + String participantDigestsJson = + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"17\"," + + "\"appliedCommitId\":\"commit-17\",\"contentDigest\":\"aggregate-17\"," + + "\"digestSchemaVersion\":1,\"abilitySchemaDigest\":\"ability-17\"}]"; + requested.setParticipantDigestsJson(participantDigestsJson); + requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); + PublishedReleaseBundle saved = fixture.repository().save(requested); + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getManifestSchemaVersion()).isEqualTo(1); + assertThat(saved.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(saved.getParticipantDigestsJson()).isEqualTo(participantDigestsJson); + assertThat(saved.getPublishedReleaseBundleRef()) + .isNotBlank() + .isNotEqualTo("caller-supplied-release-reference"); + assertThat(requested.getPublishedReleaseBundleRef()) + .isEqualTo("caller-supplied-release-reference"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + PublishedReleaseBundle stored = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + + stored.setManifestHash("sha256:" + "c".repeat(64)); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + stored.setCanonicalVersionId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + PublishedReleaseBundle persistedAfterAttempts = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + assertThat(persistedAfterAttempts.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void rejectsCallerSubstitutionWrongTenantUnmappedVersionAndContradictoryGameSource() + throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + insertVersion(fixture.dsl(), 18L, "tenant-key", null, null, null, null, null); + insertVersion( + fixture.dsl(), + 19L, + "tenant-key", + OTHER_UUID, + UUID.randomUUID(), + 8L, + "other-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle substituted = bundle("tenant-key", 17L); + substituted.setCanonicalTenantId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy(() -> fixture.repository().save(bundle("other-tenant-key", 17L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 18L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 19L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(fixture.bundleCount()).isZero(); + } + } + + private static Fixture fixture() throws Exception { + Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:published-release-bundle-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, tenant_identity_provenance_kind VARCHAR(32), " + + "tenant_identity_source_game_id BIGINT, " + + "tenant_identity_source_legacy_tenant_id VARCHAR(36))"); + dsl.execute( + "CREATE TABLE version (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, " + + "identity_source_game_row_id BIGINT, identity_source_game_tenant_key VARCHAR(36), " + + "identity_source_provenance_kind VARCHAR(32))"); + dsl.execute( + "CREATE TABLE published_release_bundle (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "published_release_bundle_ref VARCHAR(128), " + + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + + "attestation_schema_version VARCHAR(16) NOT NULL, " + + "publish_workflow_id VARCHAR(64) NOT NULL, manifest_hash VARCHAR(128) NOT NULL, " + + "generation_config_revision VARCHAR(128), " + + "required_manifest_asset_keys_json CLOB NOT NULL, " + + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "world_published_start_location_evidence_json CLOB, " + + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + + "published_at TIMESTAMP NOT NULL)"); + return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); + } + + private static void insertGame( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO game (id, tenant_id, canonical_tenant_id, " + + "tenant_identity_provenance_kind, tenant_identity_source_game_id, " + + "tenant_identity_source_legacy_tenant_id) VALUES (?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + provenanceKind, + sourceGameId, + sourceTenantKey); + } + + private static void insertVersion( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO version (id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + canonicalVersionId, + sourceGameId, + sourceTenantKey, + provenanceKind); + } + + private static PublishedReleaseBundle bundle(String tenantId, long versionId) { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(versionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("1"); + bundle.setPublishWorkflowId("workflow-" + versionId); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private record Fixture( + Connection connection, DSLContext dsl, PublishedReleaseBundleRepository repository) + implements AutoCloseable { + long bundleCount() { + return dsl.fetchCount(DSL.table(DSL.name("published_release_bundle"))); + } + + @Override + public void close() throws Exception { + connection.close(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java index 3146193994..d460daca12 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.sql.DriverManager; import java.util.ArrayList; @@ -47,6 +48,10 @@ public void executeStart(ExecuteContext context) { + "\"last_error_code\" VARCHAR(255), " + "\"last_error_message\" VARCHAR(1000), " + "\"exported_manifest_asset_keys_json\" VARCHAR(4000), " + + "\"manifest_schema_version\" INT, " + + "\"artifact_digests_json\" VARCHAR(4000), " + + "\"published_object_proofs_json\" VARCHAR(4000), " + + "\"candidate_snapshot_version_id\" BIGINT, " + "\"updated_at\" TIMESTAMP NOT NULL, " + "UNIQUE (\"tenant_id\", \"version_id\"))"); @@ -80,6 +85,31 @@ public void executeStart(ExecuteContext context) { assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); assertThat(sql.toLowerCase()).doesNotContain("version_id"); }); + + VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(dsl); + VersionAssetArtifact stale = + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow(); + inserted.setStateEpoch(3L); + inserted.setLastWorkflowId("exact-next-workflow"); + VersionAssetArtifact winner = repository.save(inserted); + assertThat(winner.getStateEpoch()).isEqualTo(3L); + assertThat(winner.getLastWorkflowId()).isEqualTo("exact-next-workflow"); + stale.setStateEpoch(3L); + stale.setLastWorkflowId("stale-workflow"); + assertThatThrownBy(() -> repository.save(stale)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow()) + .isEqualTo(winner); + winner.setTenantId("other-tenant"); + winner.setStateEpoch(4L); + assertThatThrownBy(() -> repository.save(winner)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("other-tenant", 7L)).isEmpty(); + assertThat( + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow().getStateEpoch()) + .isEqualTo(3L); } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java index ffc5d472c2..df4800fc4f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java @@ -22,6 +22,11 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible "CREATE TABLE \"version\" (" + "\"id\" BIGINT PRIMARY KEY, " + "\"tenant_id\" VARCHAR(36) NOT NULL, " + + "\"canonical_version_id\" UUID, " + + "\"canonical_tenant_id\" UUID, " + + "\"identity_source_game_row_id\" BIGINT, " + + "\"identity_source_game_tenant_key\" VARCHAR(36), " + + "\"identity_source_provenance_kind\" VARCHAR(32), " + "\"version_number\" INT NOT NULL, " + "\"version_state\" VARCHAR(32) NOT NULL, " + "\"version_state_epoch\" BIGINT NOT NULL, " @@ -58,6 +63,15 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible VersionLifecycleState.RETIRED, VersionLifecycleState.ACTIVE, VersionLifecycleState.PUBLISHED); + assertThat(candidates) + .allSatisfy( + candidate -> { + assertThat(candidate.getCanonicalVersionId()).isNull(); + assertThat(candidate.getCanonicalTenantId()).isNull(); + assertThat(candidate.getIdentitySourceGameRowId()).isNull(); + assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); + assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); + }); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index ef89325c46..340fa9b6c4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -1,13 +1,18 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; @@ -24,6 +29,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,6 +37,11 @@ import org.mockito.MockitoAnnotations; class VersionAssetArtifactServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String DIFFERENT_MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + private static final String DIFFERENT_LOGO_DIGEST = "sha256:" + "d".repeat(64); + @Mock private VersionAssetArtifactRepository repository; @Mock private VersionAssetPurgeWorkflowRepository purgeWorkflowRepository; @Mock private VersionRepository versionRepository; @@ -59,8 +70,17 @@ void setUp() { } @Test - void markExportedUnattestedCreatesArtifactStateRow() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + void markExportedUnattestedAdvancesPersistedCandidateAndExactRetryDoesNotChurn() { + VersionAssetArtifact staged = new VersionAssetArtifact(); + staged.setTenantId("tenant-1"); + staged.setVersionId(7L); + staged.setExportedVersionNumber(8); + staged.setArtifactState(VersionAssetArtifactState.STAGED); + staged.setStateEpoch(2L); + staged.setLastWorkflowId("workflow-1"); + setArtifactCandidate(staged, MANIFEST_HASH, List.of()); + when(repository.findByTenantIdAndVersionIdForUpdate("tenant-1", 7L)) + .thenReturn(Optional.of(staged)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -70,13 +90,22 @@ void markExportedUnattestedCreatesArtifactStateRow() { 7L, 8, "workflow-1", - new ExportedAssetManifest("hash-1", List.of("a", "b"))); + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); + var retry = + service.markExportedUnattested( + "tenant-1", + 7L, + 8, + "workflow-1", + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); assertEquals("EXPORTED_UNATTESTED", state.artifactState()); + assertEquals(state, retry); assertEquals(8, state.exportedVersionNumber()); - assertEquals(1L, state.stateEpoch()); - assertEquals("hash-1", state.manifestHash()); - assertEquals(List.of("a", "b"), state.exportedManifestAssetKeys()); + assertEquals(3L, state.stateEpoch()); + assertEquals(MANIFEST_HASH, state.manifestHash()); + assertEquals(List.of(), state.exportedManifestAssetKeys()); + verify(repository, times(1)).save(any(VersionAssetArtifact.class)); } @Test @@ -87,14 +116,93 @@ void optionalReadDistinguishesMissingArtifactWhileRequiredReadStillFails() { assertThrows(IllegalArgumentException.class, () -> service.getState("tenant-1", 7L)); } + @Test + void getExportCandidateReturnsNullForExactInitialStagedIntent() { + VersionAssetArtifact intent = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertNull(service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateReturnsRecordedCompleteCandidate() { + VersionAssetArtifact artifact = initialStagedIntent(); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + assertEquals( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(LOGO_DIGEST))), + service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateRejectsEachPartialCandidateField() { + for (int partialField = 0; partialField < 4; partialField++) { + VersionAssetArtifact partial = initialStagedIntent(); + switch (partialField) { + case 0 -> partial.setManifestSchemaVersion(1); + case 1 -> partial.setArtifactDigestsJson("[]"); + case 2 -> partial.setPublishedObjectProofsJson("[]"); + case 3 -> partial.setCandidateSnapshotVersionId(7L); + default -> throw new IllegalStateException("unexpected partial field"); + } + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(partial)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsNonemptyOrMalformedInitialKeys() { + for (String keysJson : List.of("[\"logo.png\"]", "not-json", " ")) { + VersionAssetArtifact intent = initialStagedIntent(); + intent.setExportedManifestAssetKeysJson(keysJson); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateDoesNotTreatOtherStatesAsInitialIntent() { + VersionAssetArtifact artifact = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + for (VersionAssetArtifactState state : VersionAssetArtifactState.values()) { + if (state == VersionAssetArtifactState.STAGED) { + continue; + } + artifact.setArtifactState(state); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsWrongOwnerScopeAndMissingArtifact() { + VersionAssetArtifact wrongOwner = initialStagedIntent(); + wrongOwner.setTenantId("tenant-2"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(wrongOwner)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + + VersionAssetArtifact wrongVersion = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 8L)) + .thenReturn(Optional.of(wrongVersion)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 8L)); + + when(repository.findByTenantIdAndVersionId("tenant-1", 9L)).thenReturn(Optional.empty()); + assertThrows(IllegalArgumentException.class, () -> service.getExportCandidate("tenant-1", 9L)); + } + @Test void repairFailsClosedWhenManifestHashDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of()); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -121,29 +229,35 @@ void repairFailsClosedWhenManifestHashDrifts() { 8, "v1", "workflow-1", - "attested", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of())); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); + .thenReturn(new ExportedAssetManifest(DIFFERENT_MANIFEST_HASH, 1, List.of(), List.of())); assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); } @Test - void repairFailsClosedWhenAttestedAssetKeysDrift() { + void repairFailsClosedWhenAttestedArtifactDigestDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -163,22 +277,29 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { 8, "v1", "workflow-1", - "attested", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), List.of(), "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof(LOGO_DIGEST)))); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(DIFFERENT_LOGO_DIGEST)))); IllegalStateException thrown = assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); - assertEquals("REPAIR_ATTESTED_ASSET_KEY_MISMATCH", thrown.getMessage()); + assertEquals("REPAIR_ATTESTATION_MISMATCH", thrown.getMessage()); } @Test @@ -189,8 +310,8 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setExportedVersionNumber(8); artifact.setStateEpoch(5L); - artifact.setManifestHash("hash-1"); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setManifestHash(MANIFEST_HASH); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -223,7 +344,7 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { assertEquals(VersionAssetPurgeWorkflowStatus.SUCCEEDED.name(), finished.workflowStatus()); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -234,7 +355,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { artifact.setExportedVersionNumber(8); artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setStateEpoch(5L); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -268,7 +389,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { service.finalizePurgeVersionAssets("tenant-1", 7L, started.purgeWorkflowId(), 6L); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -351,4 +472,56 @@ void canDeleteFailsClosedWhenApprovedRemapSetStillReferencesVersion() { assertEquals(false, eligibility.deletable()); assertEquals("VERSION_ASSET_TEMPLATE_REMAP_REFERENCE_EXISTS", eligibility.failureCode()); } + + private static PublishedArtifactDigest logoProof(String digest) { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + digest.substring("sha256:".length()), + digest, + "image/png", + 1); + } + + private static VersionAssetArtifact initialStagedIntent() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId("workflow-1"); + artifact.setExportedManifestAssetKeysJson("[]"); + return artifact; + } + + private static void setArtifactCandidate( + VersionAssetArtifact artifact, String manifestHash, List digests) { + List keys = digests.stream().map(PublishedArtifactDigest::usageKey).toList(); + List objectProofs = new ArrayList<>(); + for (PublishedArtifactDigest digest : digests) { + objectProofs.add(new StoredObjectProof(digest.immutableObjectKey(), digest.contentDigest())); + } + objectProofs.add( + new StoredObjectProof( + "manifests/sha256/" + manifestHash.substring("sha256:".length()), manifestHash)); + objectProofs.sort(java.util.Comparator.comparing(StoredObjectProof::immutableObjectKey)); + + artifact.setManifestHash(manifestHash); + artifact.setManifestSchemaVersion(1); + artifact.setExportedManifestAssetKeysJson(writeJson(keys)); + artifact.setArtifactDigestsJson(writeJson(digests)); + artifact.setPublishedObjectProofsJson(writeJson(objectProofs)); + artifact.setCandidateSnapshotVersionId(artifact.getVersionId()); + } + + private static String writeJson(Object value) { + try { + return new tools.jackson.databind.ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("failed to serialize artifact candidate proof", exception); + } + } + + private record StoredObjectProof(String immutableObjectKey, String contentDigest) {} } From 77e982dfa1571b2c8bc8d2bd780565ba0ba58c8e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:21:09 +1300 Subject: [PATCH 02/29] Preserve prepared Game Design source and complete launch contract before approved ownership cut --- .../game-design/v1/game_design_service.proto | 64 +- .../v1/world_management_service.proto | 59 + .../WorldAuthoredSourceIntakeGrpcCodec.java | 307 +++++ ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 ++++ .../dto/ResolvedLaunchDescriptorDto.java | 34 +- ...AuthoredWorldSourceDeliveryRepository.java | 604 ++++++++++ .../GameAuthoredWorldSourceRepository.java | 627 ++++++++++ .../AssetExportOutcomePendingException.java | 16 + .../service/LaunchDescriptorService.java | 24 +- .../service/impl/AssetExportServiceImpl.java | 589 +++++++--- ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 275 ++++- .../impl/LaunchDescriptorServiceImpl.java | 754 +++++++++--- .../PublishedReleaseBundleServiceImpl.java | 178 ++- .../VersionPublishCommandServiceImpl.java | 4 + ...34.1__authored_world_source_operations.sql | 224 ++++ .../V41__world_authored_source_delivery.sql | 249 ++++ ...redWorldSourceDeliveryIntegrationTest.java | 624 ++++++++++ ...dWorldSourceRepositoryIntegrationTest.java | 617 ++++++++++ ...aunchDescriptorServiceIntegrationTest.java | 1037 ++++++++++++++++- .../service/AssetExportServiceImplTest.java | 810 ++++++++++--- .../impl/GameDesignGrpcServiceAuthTest.java | 138 ++- .../impl/GameDesignGrpcServiceTest.java | 373 ++++-- .../impl/LaunchDescriptorServiceImplTest.java | 1024 +++++++++++++--- ...PublishedReleaseBundleServiceImplTest.java | 348 +++++- .../VersionPublishCommandServiceImplTest.java | 31 + .../gamesession/client/GameDesignClient.java | 27 +- .../service/impl/GameInstanceServiceImpl.java | 66 +- .../client/GameDesignClientTest.java | 45 +- .../impl/GameInstanceServiceImplTest.java | 22 + 30 files changed, 8449 insertions(+), 986 deletions(-) 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/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..081557fc54 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,6 +35,7 @@ service GameDesignService { returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); + rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -337,13 +338,16 @@ message CompareAndSetVersionStateResponse { } message ResolveLaunchDescriptorRequest { - string tenant_id = 1; + string canonical_tenant_id = 1; int64 game_template_id = 2; string control_plane_request_id = 3; optional string requested_script_patch_version = 4; 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; } message ResolveLaunchDescriptorResponse { @@ -491,11 +495,66 @@ 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 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 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; +} + +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 { string launch_descriptor_id = 1; - string tenant_id = 2; + string canonical_tenant_id = 2; int64 game_template_id = 3; string control_plane_request_id = 4; int64 version_id = 5; @@ -506,6 +565,7 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; } message TemplateRemapSet { diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index d9c7fd624c..9c62d2f349 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -34,6 +34,65 @@ 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); +} + +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; + 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; + string request_digest = 10; + string receipt_digest = 11; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; 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..577ccff3c1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java @@ -0,0 +1,307 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +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 World 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"); + } + } + } + + 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(); + } + + /** 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/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java index 251dc5129e..363db4bd74 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.gamedesign.dto; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; + public record ResolvedLaunchDescriptorDto( String launchDescriptorId, - String tenantId, + String canonicalTenantId, long gameTemplateId, String controlPlaneRequestId, long versionId, @@ -12,31 +14,5 @@ public record ResolvedLaunchDescriptorDto( long versionStateEpoch, long releaseBundleId, String publishedReleaseBundleRef, - String remapSetId) { - public ResolvedLaunchDescriptorDto( - String launchDescriptorId, - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - long versionId, - String scriptPatchVersion, - String runtimeFlagsJson, - String generationConfigRevision, - long versionStateEpoch, - long releaseBundleId, - String publishedReleaseBundleRef) { - this( - launchDescriptorId, - tenantId, - gameTemplateId, - controlPlaneRequestId, - versionId, - scriptPatchVersion, - runtimeFlagsJson, - generationConfigRevision, - versionStateEpoch, - releaseBundleId, - publishedReleaseBundleRef, - null); - } -} + String remapSetId, + AuthoredWorldLaunchDescriptorEvidence authoredWorldBinding) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java new file mode 100644 index 0000000000..038acbf4bc --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java @@ -0,0 +1,604 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +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.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +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; + +/** Durable Game Design outbox for exact, fresh authored-world source delivery to World. */ +@Repository +public class GameAuthoredWorldSourceDeliveryRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final int MAX_PENDING_BATCH_SIZE = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table DELIVERY = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final Field DELIVERY_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field DELIVERY_SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field DELIVERY_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field DELIVERY_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field DELIVERY_SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field DELIVERY_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field DELIVERY_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field DELIVERY_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field DELIVERY_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field DELIVERY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field DELIVERY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field DELIVERY_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field DELIVERY_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DELIVERY_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("intake_schema_version"), Integer.class); + private static final Field DELIVERY_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field DELIVERY_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + private static final Field DELIVERY_WORLD_REQUEST_DIGEST = + DSL.field(DSL.name("world_request_digest"), String.class); + private static final Field DELIVERY_WORLD_RECEIPT_DIGEST = + DSL.field(DSL.name("world_receipt_digest"), String.class); + private static final Field DELIVERY_ACKNOWLEDGED_AT = + DSL.field(DSL.name("acknowledged_at"), OffsetDateTime.class); + + private static final Table SOURCE = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field SOURCE_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_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("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_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 final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected DSLContext is the repository's owner transaction collaborator.") + public GameAuthoredWorldSourceDeliveryRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Persists one stable World intake identity inside the source-registration transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim enqueueFresh(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + requireExactPersistedSource(source); + + Record existing = findDelivery(source.operationId()); + if (existing != null) { + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + return claim; + } + + UUID intakeRequestId = UUID.randomUUID(); + while (NIL_UUID.equals(intakeRequestId) || source.operationId().equals(intakeRequestId)) { + intakeRequestId = UUID.randomUUID(); + } + IntakeRequest request = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + intakeRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + String intakeRequestDigest = WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request); + + int inserted = + dsl.insertInto(DELIVERY) + .set(DELIVERY_SOURCE_OPERATION_ID, source.operationId()) + .set(DELIVERY_SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(DELIVERY_NAMESPACE, source.targetNamespace()) + .set(DELIVERY_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(DELIVERY_SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(DELIVERY_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(DELIVERY_TENANT_SLUG, source.tenantSlug()) + .set(DELIVERY_WORLD_SLUG, source.worldSlug()) + .set(DELIVERY_WORLD_DISPLAY_NAME, source.worldDisplayName()) + .set(DELIVERY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(DELIVERY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(DELIVERY_PROVENANCE_KIND, source.provenanceKind()) + .set(DELIVERY_SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .set(DELIVERY_INTAKE_SCHEMA_VERSION, request.schemaVersion()) + .set(DELIVERY_INTAKE_REQUEST_ID, request.intakeRequestId()) + .set(DELIVERY_INTAKE_REQUEST_DIGEST, intakeRequestDigest) + .onConflictDoNothing() + .execute(); + if (inserted != 1) { + Record conflict = findDelivery(source.operationId()); + if (conflict != null) { + DeliveryClaim claim = toClaim(conflict); + requireSameSource(source, claim.source()); + return claim; + } + throw new DeliveryConflictException( + "Authored-world source delivery conflicts with an existing owner claim"); + } + + Record persisted = findDelivery(source.operationId()); + if (persisted == null) { + throw new IllegalStateException("Authored-world source delivery claim is missing"); + } + DeliveryClaim claim = toClaim(persisted); + requireSameSource(source, claim.source()); + if (!request.equals(claim.request()) || claim.acknowledgedReceipt().isPresent()) { + throw new DeliveryConflictException( + "Committed authored-world source delivery differs from its original claim"); + } + return claim; + } + + /** Reads one complete committed delivery claim without allocating or repairing it. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(UUID sourceOperationId) { + requireNonNil(sourceOperationId, "sourceOperationId"); + requireCommittedOutcomeRead(); + Record record = findDelivery(sourceOperationId); + if (record == null) { + return Optional.empty(); + } + DeliveryClaim claim = toClaim(record); + requireExactPersistedSource(claim.source()); + return Optional.of(claim); + } + + /** + * Reads one bounded page of exact pending claims for this workload namespace. The stable intake + * request identity is the keyset cursor; callers cycle back to the beginning after reaching the + * end so a failed older claim cannot starve later claims. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public List readPending( + String targetNamespace, UUID afterIntakeRequestId, int limit) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + if (afterIntakeRequestId != null) { + requireNonNil(afterIntakeRequestId, "afterIntakeRequestId"); + } + if (limit < 1 || limit > MAX_PENDING_BATCH_SIZE) { + throw new IllegalArgumentException( + "Pending authored-world delivery page size must be between 1 and " + + MAX_PENDING_BATCH_SIZE); + } + requireCommittedOutcomeRead(); + + var rows = + dsl.selectFrom(DELIVERY) + .where( + DELIVERY_NAMESPACE + .eq(targetNamespace) + .and(DELIVERY_PROVENANCE_KIND.eq(NEW_GAME_ROW)) + .and(DELIVERY_WORLD_OPERATION_ID.isNull()) + .and(DELIVERY_WORLD_REQUEST_DIGEST.isNull()) + .and(DELIVERY_WORLD_RECEIPT_DIGEST.isNull()) + .and(DELIVERY_ACKNOWLEDGED_AT.isNull()) + .and( + afterIntakeRequestId == null + ? DSL.noCondition() + : DELIVERY_INTAKE_REQUEST_ID.gt(afterIntakeRequestId))) + .orderBy(DELIVERY_INTAKE_REQUEST_ID.asc()) + .limit(limit) + .fetch(); + List claims = new ArrayList<>(rows.size()); + for (Record row : rows) { + DeliveryClaim claim = toClaim(row); + if (!targetNamespace.equals(claim.request().targetNamespace()) + || claim.acknowledgedReceipt().isPresent()) { + throw new DeliveryConflictException( + "Pending authored-world delivery read returned a claim outside its exact selector"); + } + requireExactPersistedSource(claim.source()); + claims.add(claim); + } + return List.copyOf(claims); + } + + /** Records only the first full World receipt, or returns an identical concurrent winner. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim acknowledge(DeliveryClaim expected, CommittedReceipt receipt) { + requireActiveWritableOwnerTransaction(); + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(receipt, "receipt"); + requireFreshSource(expected.source()); + requireReceiptMatchesRequest(expected.request(), receipt); + + Record currentRecord = findDelivery(expected.source().operationId()); + if (currentRecord == null) { + throw new DeliveryConflictException("Authored-world source delivery claim is missing"); + } + DeliveryClaim current = toClaim(currentRecord); + requireSameClaim(expected, current); + requireExactPersistedSource(current.source()); + if (current.acknowledgedReceipt().isPresent()) { + CommittedReceipt original = current.acknowledgedReceipt().orElseThrow(); + if (!original.equals(receipt)) { + throw new DeliveryConflictException( + "Authored-world source delivery already has a different World receipt"); + } + return current; + } + + int updated = + dsl.update(DELIVERY) + .set(DELIVERY_WORLD_OPERATION_ID, receipt.operationId()) + .set(DELIVERY_WORLD_REQUEST_DIGEST, receipt.requestDigest()) + .set(DELIVERY_WORLD_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(DELIVERY_ACKNOWLEDGED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where( + DELIVERY_SOURCE_OPERATION_ID + .eq(expected.source().operationId()) + .and(DELIVERY_WORLD_OPERATION_ID.isNull()) + .and(DELIVERY_WORLD_REQUEST_DIGEST.isNull()) + .and(DELIVERY_WORLD_RECEIPT_DIGEST.isNull()) + .and(DELIVERY_ACKNOWLEDGED_AT.isNull())) + .execute(); + if (updated > 1) { + throw new IllegalStateException("Authored-world source delivery ACK changed multiple rows"); + } + + Record acknowledgedRecord = findDelivery(expected.source().operationId()); + if (acknowledgedRecord == null) { + throw new IllegalStateException("Authored-world source delivery disappeared during ACK"); + } + DeliveryClaim acknowledged = toClaim(acknowledgedRecord); + requireSameClaim(expected, acknowledged); + CommittedReceipt durableReceipt = + acknowledged + .acknowledgedReceipt() + .orElseThrow( + () -> new DeliveryConflictException("World receipt ACK did not read back")); + if (!durableReceipt.equals(receipt)) { + throw new DeliveryConflictException( + "Concurrent authored-world source delivery ACK has a different World receipt"); + } + return acknowledged; + } + + /** Validates a pre-V41 registration retry when its optional delivery row already exists. */ + @Transactional(propagation = Propagation.MANDATORY) + void validateExistingIfPresent(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + Record existing = findDelivery(source.operationId()); + if (existing == null) { + return; + } + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + } + + private Record findDelivery(UUID sourceOperationId) { + return dsl.selectFrom(DELIVERY) + .where(DELIVERY_SOURCE_OPERATION_ID.eq(sourceOperationId)) + .fetchOne(); + } + + private DeliveryClaim toClaim(Record row) { + AuthoredWorldSourceEvidence source; + IntakeRequest request; + Optional acknowledgedReceipt; + try { + source = + new AuthoredWorldSourceEvidence( + row.get(DELIVERY_SOURCE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_REGISTRATION_REQUEST_ID), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_REQUEST_DIGEST), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_TENANT_SLUG), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_WORLD_DISPLAY_NAME), + row.get(DELIVERY_SOURCE_GAME_ROW_ID), + row.get(DELIVERY_SOURCE_GAME_TENANT_KEY), + row.get(DELIVERY_PROVENANCE_KIND), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + request = + new IntakeRequest( + row.get(DELIVERY_INTAKE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_INTAKE_REQUEST_ID), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request) + .equals(row.get(DELIVERY_INTAKE_REQUEST_DIGEST))) { + throw new IllegalArgumentException("Persisted World intake request digest is invalid"); + } + UUID worldOperationId = row.get(DELIVERY_WORLD_OPERATION_ID); + String worldRequestDigest = row.get(DELIVERY_WORLD_REQUEST_DIGEST); + String worldReceiptDigest = row.get(DELIVERY_WORLD_RECEIPT_DIGEST); + if (worldOperationId == null && worldRequestDigest == null && worldReceiptDigest == null) { + acknowledgedReceipt = Optional.empty(); + } else { + acknowledgedReceipt = + Optional.of( + new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + worldRequestDigest, + worldReceiptDigest)); + } + return new DeliveryClaim(source, request, acknowledgedReceipt); + } catch (RuntimeException exception) { + if (exception instanceof DeliveryConflictException conflict) { + throw conflict; + } + throw new InvalidDeliveryClaimException( + "Persisted authored-world source delivery claim is invalid", exception); + } + } + + private void requireExactPersistedSource(AuthoredWorldSourceEvidence expected) { + Record sourceRow = + dsl.selectFrom(SOURCE).where(SOURCE_OPERATION_ID.eq(expected.operationId())).fetchOne(); + if (sourceRow == null || !expected.equals(toSourceEvidence(sourceRow))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery does not match the complete persisted source receipt"); + } + + Record gameRow = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(expected.sourceGameRowId())) + .fetchOne(); + if (gameRow == null + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_TENANT_ID)) + || !expected.canonicalTenantId().equals(gameRow.get(GAME_CANONICAL_TENANT_ID)) + || !expected.provenanceKind().equals(gameRow.get(GAME_PROVENANCE_KIND)) + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_SOURCE_ROW_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_SOURCE_TENANT_KEY))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its Game Design game row"); + } + + Record bindingRow = + dsl.select( + BINDING_NAMESPACE, + BINDING_CANONICAL_TENANT_ID, + BINDING_TENANT_SLUG, + BINDING_SOURCE_GAME_ROW_ID, + BINDING_SOURCE_GAME_TENANT_KEY, + BINDING_PROVENANCE_KIND) + .from(TENANT_BINDING) + .where( + BINDING_NAMESPACE + .eq(expected.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(expected.canonicalTenantId()))) + .fetchOne(); + if (bindingRow == null + || !expected.tenantSlug().equals(bindingRow.get(BINDING_TENANT_SLUG)) + || !Long.valueOf(expected.sourceGameRowId()) + .equals(bindingRow.get(BINDING_SOURCE_GAME_ROW_ID)) + || !expected.sourceGameTenantKey().equals(bindingRow.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !expected.provenanceKind().equals(bindingRow.get(BINDING_PROVENANCE_KIND))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its tenant selector binding"); + } + } + + private AuthoredWorldSourceEvidence toSourceEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(SOURCE_SCHEMA_VERSION), + row.get(SOURCE_NAMESPACE), + row.get(SOURCE_REGISTRATION_REQUEST_ID), + row.get(SOURCE_OPERATION_ID), + row.get(SOURCE_REQUEST_DIGEST), + row.get(SOURCE_CANONICAL_TENANT_ID), + row.get(SOURCE_TENANT_SLUG), + row.get(SOURCE_WORLD_SLUG), + row.get(SOURCE_WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(SOURCE_PROVENANCE_KIND), + row.get(SOURCE_EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidDeliveryClaimException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private static void requireSameClaim(DeliveryClaim expected, DeliveryClaim actual) { + requireSameSource(expected.source(), actual.source()); + if (!expected.request().equals(actual.request())) { + throw new DeliveryConflictException( + "Authored-world source delivery request identity changed after dispatch"); + } + } + + private static void requireSameSource( + AuthoredWorldSourceEvidence expected, AuthoredWorldSourceEvidence actual) { + if (!expected.equals(actual)) { + throw new DeliveryConflictException( + "Authored-world source delivery no longer matches its immutable source evidence"); + } + } + + private static void requireReceiptMatchesRequest( + IntakeRequest request, CommittedReceipt 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())) { + throw new DeliveryConflictException( + "World receipt does not bind the exact persisted authored-world source request"); + } + } + + private static void requireFreshSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + if (!NEW_GAME_ROW.equals(source.provenanceKind())) { + throw new DeliveryConflictException( + "Only a proven NEW_GAME_ROW authored-world source may be delivered to World"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireActiveWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Authored-world source delivery mutation requires an active writable owner transaction"); + } + } + + private static void requireCommittedOutcomeRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery read requires a committed-outcome owner read"); + } + } + + /** Exact persisted source, immutable World intake identity, and first optional World ACK. */ + public record DeliveryClaim( + AuthoredWorldSourceEvidence source, + IntakeRequest request, + Optional acknowledgedReceipt) { + public DeliveryClaim { + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(acknowledgedReceipt, "acknowledgedReceipt"); + requireFreshSource(source); + IntakeRequest expected = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + request.intakeRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + if (!expected.equals(request)) { + throw new DeliveryConflictException( + "World intake request does not bind the complete authored-world source"); + } + acknowledgedReceipt.ifPresent(receipt -> requireReceiptMatchesRequest(request, receipt)); + } + } + + public static class DeliveryConflictException extends IllegalStateException { + public DeliveryConflictException(String message) { + super(message); + } + } + + public static final class InvalidDeliveryClaimException extends DeliveryConflictException { + public InvalidDeliveryClaimException(String message) { + super(message); + } + + public InvalidDeliveryClaimException(String message, Throwable cause) { + super(message); + initCause(cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..a2a7947737 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java @@ -0,0 +1,627 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local immutable selector-source registration and exact committed readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class GameAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final String RETAINED_GAME_V29 = "RETAINED_GAME_V29"; + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_SLUG_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_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 OPERATION = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + 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 REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("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 PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; + private final GameAuthoredWorldSourceDeliveryRepository deliveryRepository; + + @Autowired + public GameAuthoredWorldSourceRepository( + DSLContext dsl, GameAuthoredWorldSourceDeliveryRepository deliveryRepository) { + this.dsl = dsl; + this.deliveryRepository = deliveryRepository; + } + + /** Retains the direct owner-test construction path while sharing its owner DSL context. */ + public GameAuthoredWorldSourceRepository(DSLContext dsl) { + this(dsl, new GameAuthoredWorldSourceDeliveryRepository(dsl)); + } + + /** + * Binds explicit authored-world selectors to one exact persisted Game Design tenant source. + * + *

The caller must own the encompassing Game Design transaction. The actual source game row is + * locked before request replay checks and selector claims, serializing registrations for one + * tenant without treating a template, display name, or legacy key as a selector. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + requireActiveOwnerTransaction(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + + GameSource source = lockGameSource(canonicalTenantId); + if (source == null) { + throw new RegistrationConflictException("Canonical tenant source game row is missing"); + } + requireConsistentGameSource(source); + + Record existingRequest = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (existingRequest != null) { + AuthoredWorldSourceEvidence receipt = toEvidence(existingRequest); + if (!requestDigest.equals(receipt.requestDigest()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !tenantSlug.equals(receipt.tenantSlug()) + || !worldSlug.equals(receipt.worldSlug()) + || !worldDisplayName.equals(receipt.worldDisplayName())) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + // A missing pre-V41 delivery claim stays missing; exact source retry does not backfill it. + deliveryRepository.validateExistingIfPresent(receipt); + } + return receipt; + } + + ensureTenantSlugBinding(targetNamespace, tenantSlug, source); + UUID operationId = UUID.randomUUID(); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + source.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + + int inserted = + dsl.insertInto(OPERATION) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, targetNamespace) + .set(REGISTRATION_REQUEST_ID, registrationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, tenantSlug) + .set(WORLD_SLUG, worldSlug) + .set(WORLD_DISPLAY_NAME, worldDisplayName) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(PROVENANCE_KIND, source.provenanceKind()) + .set(EVIDENCE_DIGEST, evidenceDigest) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record requestConflict = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (requestConflict != null) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + Record selectorConflict = findByWorldSelector(targetNamespace, canonicalTenantId, worldSlug); + if (selectorConflict != null) { + throw new RegistrationConflictException( + "Authored-world selector is already owned by another source operation"); + } + throw new RegistrationConflictException( + "Authored-world source operation conflicts with an existing owner claim"); + } + + Record persisted = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source operation is missing"); + } + AuthoredWorldSourceEvidence receipt = toEvidence(persisted); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + deliveryRepository.enqueueFresh(receipt); + } + return receipt; + } + + /** Reads one exact committed source operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID operationId, UUID canonicalTenantId, String worldSlug, String targetNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (operationId == null || operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be a canonical non-nil UUID"); + } + Record record = + dsl.selectFrom(OPERATION) + .where( + OPERATION_ID + .eq(operationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(targetNamespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(record); + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source row is missing"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return Optional.of(receipt); + } + + /** + * Reads the exact source receipt and its source-owned version from the caller's owner snapshot. + * + *

This method is intentionally separate from {@link #read}: the latter suspends any ambient + * transaction to read a committed outcome, while this owner-current read requires the dedicated + * read-only REPEATABLE_READ transaction opened by AuthoredWorldVersionStateService. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readVersionStateSnapshot( + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + requireOwnerSnapshot(); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException("Expected source evidence digest is not canonical"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + + Record sourceRecord = + dsl.selectFrom(OPERATION).where(OPERATION_ID.eq(sourceOperationId)).fetchOne(); + if (sourceRecord == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(sourceRecord); + if (!targetNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.operationId())) { + throw new InvalidSourceEvidenceException( + "Authored-world source operation does not match the exact requested scope"); + } + if (!expectedSourceEvidenceDigest.equals(receipt.evidenceDigest())) { + throw new InvalidSourceEvidenceException( + "Authored-world source evidence digest no longer matches the requested binding"); + } + + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source game row is missing"); + } + requireConsistentGameSource(source); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + + Record versionRecord = + dsl.select( + VERSION_ID, + VERSION_TENANT_ID, + VERSION_CANONICAL_VERSION_ID, + VERSION_CANONICAL_TENANT_ID, + VERSION_IDENTITY_SOURCE_GAME_ROW_ID, + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY, + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND, + VERSION_STATE, + VERSION_STATE_EPOCH) + .from(VERSION) + .where(VERSION_ID.eq(versionId)) + .fetchOne(); + if (versionRecord == null) { + return Optional.empty(); + } + String versionTenantId = versionRecord.get(VERSION_TENANT_ID); + if (versionTenantId == null || !source.sourceGameTenantKey().equals(versionTenantId)) { + throw new InvalidSourceEvidenceException( + "Requested version is not owned by the exact Game Design source game"); + } + UUID canonicalVersionId = versionRecord.get(VERSION_CANONICAL_VERSION_ID); + if (canonicalVersionId == null || NIL_UUID.equals(canonicalVersionId)) { + throw new InvalidSourceEvidenceException( + "Requested version has no persisted canonical non-nil Version UUID"); + } + if (!source.canonicalTenantId().equals(versionRecord.get(VERSION_CANONICAL_TENANT_ID)) + || !Long.valueOf(source.sourceGameRowId()) + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_ROW_ID)) + || !source + .sourceGameTenantKey() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + || !source + .provenanceKind() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_PROVENANCE_KIND))) { + throw new InvalidSourceEvidenceException( + "Requested version canonical identity provenance does not match " + + "the exact Game Design source game"); + } + + VersionLifecycleState versionState; + Long versionStateEpoch = versionRecord.get(VERSION_STATE_EPOCH); + try { + String versionStateName = versionRecord.get(VERSION_STATE); + if (versionStateName == null || versionStateEpoch == null || versionStateEpoch <= 0) { + throw new IllegalArgumentException("Version lifecycle state or epoch is invalid"); + } + versionState = VersionLifecycleState.valueOf(versionStateName); + } catch (IllegalArgumentException exception) { + throw new InvalidSourceEvidenceException( + "Persisted version lifecycle state or epoch is invalid", exception); + } + return Optional.of( + new AuthoredWorldVersionStateSnapshot( + receipt, canonicalVersionId, versionState, versionStateEpoch)); + } + + private void ensureTenantSlugBinding( + String targetNamespace, String tenantSlug, GameSource source) { + Record existing = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (existing != null) { + requireMatchingBinding(existing, targetNamespace, tenantSlug, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_SLUG_BINDING) + .set(BINDING_NAMESPACE, targetNamespace) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, 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 = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, targetNamespace, tenantSlug, source); + return; + } + Record slugOwner = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where(BINDING_NAMESPACE.eq(targetNamespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + if (slugOwner != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + throw new RegistrationConflictException( + "Tenant selector binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence receipt) { + Record binding = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(receipt.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(receipt.canonicalTenantId()))) + .fetchOne(); + if (binding == null) { + throw new InvalidSourceEvidenceException("Tenant selector binding is missing"); + } + requireMatchingBinding( + binding, + receipt.targetNamespace(), + receipt.tenantSlug(), + new GameSource( + receipt.sourceGameRowId(), + receipt.canonicalTenantId(), + receipt.sourceGameTenantKey(), + receipt.provenanceKind())); + } + + private void requireMatchingBinding( + Record binding, String targetNamespace, String tenantSlug, GameSource source) { + if (!targetNamespace.equals(binding.get(BINDING_NAMESPACE)) + || !source.canonicalTenantId().equals(binding.get(BINDING_CANONICAL_TENANT_ID)) + || !tenantSlug.equals(binding.get(BINDING_TENANT_SLUG)) + || source.sourceGameRowId() != binding.get(BINDING_SOURCE_GAME_ROW_ID) + || !source.sourceGameTenantKey().equals(binding.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !source.provenanceKind().equals(binding.get(BINDING_PROVENANCE_KIND))) { + throw new RegistrationConflictException( + "Canonical tenant already has a different stable tenant selector or source tuple"); + } + } + + private Record findByRegistrationRequest(String targetNamespace, UUID registrationRequestId) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(REGISTRATION_REQUEST_ID.eq(registrationRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private GameSource lockGameSource(UUID canonicalTenantId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .forUpdate() + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource findGameSourceByRow(long sourceGameRowId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(sourceGameRowId)) + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource gameSource(Record row) { + Long id = row.get(GAME_ID); + String tenantKey = row.get(GAME_TENANT_ID); + UUID canonicalTenantId = row.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = row.get(GAME_PROVENANCE_KIND); + Long provenanceRowId = row.get(GAME_SOURCE_ROW_ID); + String provenanceTenantKey = row.get(GAME_SOURCE_TENANT_KEY); + if (id == null + || tenantKey == null + || canonicalTenantId == null + || provenanceKind == null + || provenanceRowId == null + || provenanceTenantKey == null + || !id.equals(provenanceRowId) + || !tenantKey.equals(provenanceTenantKey)) { + throw new InvalidSourceEvidenceException( + "Game Design tenant source provenance does not match its game row"); + } + return new GameSource(id, canonicalTenantId, tenantKey, provenanceKind); + } + + private void requireConsistentGameSource(GameSource source) { + if (!NEW_GAME_ROW.equals(source.provenanceKind()) + && !RETAINED_GAME_V29.equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException("Game Design tenant provenance is not recognized"); + } + } + + private void requireReceiptSource(AuthoredWorldSourceEvidence receipt, GameSource source) { + if (receipt.sourceGameRowId() != source.sourceGameRowId() + || !receipt.canonicalTenantId().equals(source.canonicalTenantId()) + || !receipt.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !receipt.provenanceKind().equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException( + "Authored-world source tuple no longer matches its Game Design row"); + } + } + + private AuthoredWorldSourceEvidence toEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(OPERATION_SCHEMA_VERSION), + row.get(OPERATION_NAMESPACE), + row.get(REGISTRATION_REQUEST_ID), + row.get(OPERATION_ID), + row.get(REQUEST_DIGEST), + row.get(CANONICAL_TENANT_ID), + row.get(TENANT_SLUG), + row.get(WORLD_SLUG), + row.get(WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(PROVENANCE_KIND), + row.get(EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidSourceEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source registration requires an active Game Design owner transaction"); + } + } + + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Authored-world version-state read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + public record AuthoredWorldVersionStateSnapshot( + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) {} + + private record GameSource( + long sourceGameRowId, + UUID canonicalTenantId, + String sourceGameTenantKey, + String provenanceKind) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidSourceEvidenceException extends IllegalStateException { + public InvalidSourceEvidenceException(String message) { + super(message); + } + + public InvalidSourceEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java new file mode 100644 index 0000000000..3708b6563b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.gamedesign.service; + +/** + * Indicates that an immutable object write may have committed but exact readback is unavailable. + */ +public final class AssetExportOutcomePendingException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public AssetExportOutcomePendingException(String message, Throwable cause) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message, cause); + } + + public AssetExportOutcomePendingException(String message) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..cf337ee6e8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -1,14 +1,26 @@ package net.firedevops.firemud.gamedesign.service; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; public interface LaunchDescriptorService { ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, + AuthoredWorldLaunchDescriptorEvidence.Request request); + + ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); + + ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java index fd21101b9d..05e2c48a38 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java @@ -2,217 +2,516 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; import java.util.List; -import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import org.springframework.stereotype.Service; +import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import tools.jackson.databind.ObjectMapper; @Service @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators remain internal service dependencies") + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects missing collaborators before publication; this bean has no finalizer") public class AssetExportServiceImpl implements AssetExportService { private static final String ASSET_USAGE_KEY_COLLISION = "ASSET_USAGE_KEY_COLLISION"; - private static final String EXPORT_SNAPSHOT_CAPACITY = "EXPORT_SNAPSHOT_CAPACITY"; - private static final String MANIFEST_OBJECT_KEY = "manifest.json"; - private static final String REPAIR_VERSION_SCOPE_UNAVAILABLE = "REPAIR_VERSION_SCOPE_UNAVAILABLE"; + private static final String SNAPSHOT_UNAVAILABLE = "VERSION_ASSET_SNAPSHOT_UNAVAILABLE"; + private static final String SNAPSHOT_MISMATCH = "VERSION_ASSET_SNAPSHOT_MISMATCH"; + private static final String SNAPSHOT_INVALID = "VERSION_ASSET_SNAPSHOT_INVALID"; + private static final String SOURCE_BYTES_MISMATCH = "ASSET_SOURCE_BYTES_MISMATCH"; + private static final String PUBLIC_BASE_URL_INVALID = "ASSET_STORE_PUBLIC_BASE_URL_INVALID"; + private static final String IMMUTABLE_OBJECT_CONFLICT = "IMMUTABLE_OBJECT_CONFLICT"; + private static final String MANIFEST_CONTENT_TYPE = "application/json"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final UUID NIL_UUID = new UUID(0L, 0L); - private final GameAssetRepository repository; - private final VersionRepository versionRepository; - private final Map frozenSnapshots; + private static final Comparator USAGE_KEY_ORDER = + (left, right) -> + PublishedArtifactDigest.compareUsageKeysUtf8(left.usageKey(), right.usageKey()); + + private final VersionAssetPublicationService publicationService; + + private final VersionAssetExportCandidateService candidateService; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; private final AssetStoreProperties properties; - private final ObjectMapper objectMapper; public AssetExportServiceImpl( - GameAssetRepository repository, + VersionAssetPublicationService publicationService, + VersionAssetExportCandidateService candidateService, S3Client s3Client, - AssetStoreProperties properties, - ObjectMapper objectMapper, - VersionRepository versionRepository) { - this.repository = repository; - this.versionRepository = versionRepository; - this.s3Client = s3Client; - this.properties = copyProperties(properties); - this.objectMapper = objectMapper; - this.frozenSnapshots = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true)); + AssetStoreProperties properties) { + this.publicationService = Objects.requireNonNull(publicationService); + this.candidateService = Objects.requireNonNull(candidateService); + this.s3Client = Objects.requireNonNull(s3Client); + this.properties = copyProperties(Objects.requireNonNull(properties)); } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { AssetStoreProperties copy = new AssetStoreProperties(); copy.setEndpoint(source.getEndpoint()); + copy.setPublicBaseUrl(source.getPublicBaseUrl()); copy.setBucket(source.getBucket()); copy.setRegion(source.getRegion()); copy.setAccessKey(source.getAccessKey()); copy.setSecretKey(source.getSecretKey()); - copy.setFrozenSnapshotCacheMaxEntries(source.getFrozenSnapshotCacheMaxEntries()); return copy; } @Override @Timed("gamedesign.asset.export") - public ExportedAssetManifest exportAssets(String tenantId, int version) { - VersionResolution resolution = resolveVersionScope(tenantId, version); - FrozenAssetSnapshot snapshot = resolveSnapshot(resolution.scope(), resolution.versionState()); - String prefix = tenantId + "/" + version + "/"; - Map manifest = new LinkedHashMap<>(); - ArrayList requiredManifestAssetKeys = new ArrayList<>(); - for (FrozenAsset asset : snapshot.assets()) { - String key = prefix + asset.fileName(); + public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + } + requireObjectStoreBucket(); + + ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + List selections = validateAndOrderSnapshot(frozen, tenantId, versionNumber); + + String publicBaseUrl = requireApprovedPublicBaseUrl(); + List artifacts = + selections.stream() + .map( + selection -> prepareArtifact(selection, publicBaseUrl, frozen.canonicalVersionId())) + .toList(); + byte[] manifestBytes = serializeManifest(artifacts); + String manifestHash = "sha256:" + sha256Hex(manifestBytes); + String manifestObjectKey = MANIFEST_OBJECT_ROOT + manifestHash.substring("sha256:".length()); + + List artifactDigests = + artifacts.stream().map(PreparedArtifact::digest).toList(); + List requiredManifestAssetKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + ExportedAssetManifest candidate = + new ExportedAssetManifest(manifestHash, 1, requiredManifestAssetKeys, artifactDigests); + + requireDurableCandidate(tenantId, versionNumber, candidate); + + // Candidate metadata and object proofs are durable before any private object write. + // This producer does not transition lifecycle state or expose a release. + for (PreparedArtifact artifact : artifacts) { + writeAndVerifyImmutableObject( + artifact.digest().immutableObjectKey(), + artifact.bytes(), + artifact.digest().contentType()); + } + writeAndVerifyImmutableObject(manifestObjectKey, manifestBytes, MANIFEST_CONTENT_TYPE); + return candidate; + } + + private void requireDurableCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest recorded; + try { + recorded = candidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } catch (RuntimeException exception) { + throw candidateFailure("record", exception); + } + requireCandidateMatch("record", candidate, recorded); + + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + + private RuntimeException candidateFailure(String operation, RuntimeException cause) { + if (isCandidateConflict(cause)) { + return cause; + } + return new AssetExportOutcomePendingException( + "export candidate " + operation + " outcome is unresolved", cause); + } + + private void requireCandidateMatch( + String operation, ExportedAssetManifest expected, ExportedAssetManifest actual) { + if (actual == null) { + throw new AssetExportOutcomePendingException( + "export candidate " + operation + " readback is missing"); + } + if (!expected.equals(actual)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } + + private static boolean isCandidateConflict(RuntimeException exception) { + for (Throwable current = exception; current != null; current = current.getCause()) { + if ("ASSET_EXPORT_CANDIDATE_CONFLICT".equals(current.getMessage())) { + return true; + } + } + return false; + } + + private List validateAndOrderSnapshot( + ExportSnapshot snapshot, String requestedTenantId, int requestedVersionNumber) { + if (!Objects.equals(requestedTenantId, snapshot.tenantId()) + || requestedVersionNumber != snapshot.versionNumber() + || snapshot.versionId() <= 0 + || snapshot.capturedVersionStateEpoch() <= 0 + || !isCanonicalUuid(snapshot.canonicalTenantId()) + || !isCanonicalUuid(snapshot.canonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete or out-of-scope snapshot"); + } + + Set usageKeys = new HashSet<>(); + Set sourceAssetIds = new HashSet<>(); + ArrayList ordered = new ArrayList<>(snapshot.items().size()); + for (AssetSelection selection : snapshot.items()) { + if (selection == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": null selection"); + } + String usageKey = selection.usageKey(); + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + requireCanonicalText(usageKey, "usageKey"); + if ("manifest.json".equals(usageKey) || !usageKeys.add(usageKey)) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + if (selection.assetId() <= 0 + || selection.bytes() == null + || selection.contentType() == null + || selection.contentType().isBlank() + || !selection.contentType().equals(selection.contentType().trim()) + || selection.contentType().contains("\r") + || selection.contentType().contains("\n")) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete source asset identity"); + } + if (!sourceAssetIds.add(selection.assetId())) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": duplicate source asset identity"); + } + requireCanonicalText(selection.contentType(), "contentType"); + requireCanonicalText(selection.contentDigest(), "contentDigest"); + String actualDigest = "sha256:" + sha256Hex(selection.bytes()); + if (!actualDigest.equals(selection.contentDigest())) { + throw new IllegalStateException(SOURCE_BYTES_MISMATCH); + } + ordered.add(selection); + } + ordered.sort(USAGE_KEY_ORDER); + return List.copyOf(ordered); + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private void requireObjectStoreBucket() { + if (properties.getBucket() == null || properties.getBucket().isBlank()) { + throw new IllegalStateException("ASSET_STORE_BUCKET_INVALID"); + } + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": " + fieldName + " is blank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " has control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " is not valid UTF-8", exception); + } + } + + private void requireSameSnapshot(ExportSnapshot frozen, ExportSnapshot readback) { + boolean sameScope = + Objects.equals(frozen.tenantId(), readback.tenantId()) + && frozen.versionId() == readback.versionId() + && frozen.versionNumber() == readback.versionNumber() + && frozen.capturedVersionStateEpoch() == readback.capturedVersionStateEpoch() + && Objects.equals(frozen.canonicalTenantId(), readback.canonicalTenantId()) + && Objects.equals(frozen.canonicalVersionId(), readback.canonicalVersionId()); + if (!sameScope || frozen.items() == null || readback.items() == null) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + List frozenItems = frozen.items(); + List readbackItems = readback.items(); + if (frozenItems.size() != readbackItems.size()) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + for (int index = 0; index < frozenItems.size(); index++) { + AssetSelection left = frozenItems.get(index); + AssetSelection right = readbackItems.get(index); + if (left == null + || right == null + || !Objects.equals(left.usageKey(), right.usageKey()) + || left.assetId() != right.assetId() + || !Objects.equals(left.contentType(), right.contentType()) + || !Objects.equals(left.contentDigest(), right.contentDigest()) + || !Arrays.equals(left.bytes(), right.bytes())) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + } + } + + private PreparedArtifact prepareArtifact( + AssetSelection selection, String publicBaseUrl, UUID canonicalVersionId) { + byte[] bytes = selection.bytes(); + String contentHash = sha256Hex(bytes); + String digest = "sha256:" + contentHash; + String immutableObjectKey = ARTIFACT_OBJECT_ROOT + contentHash; + String url = publicBaseUrl + "/" + immutableObjectKey; + + PublishedArtifactDigest artifactDigest = + new PublishedArtifactDigest( + selection.usageKey(), "BINARY", immutableObjectKey, digest, selection.contentType(), 1); + return new PreparedArtifact(artifactDigest, bytes, canonicalVersionId, url); + } + + private static byte[] serializeManifest(List artifacts) { + StringBuilder manifest = new StringBuilder("{\"schemaVersion\":1,\"assets\":{"); + boolean first = true; + for (PreparedArtifact artifact : artifacts) { + if (!first) { + manifest.append(','); + } + first = false; + appendJsonString(manifest, artifact.digest().usageKey()); + manifest.append(":{"); + appendJsonField(manifest, "usageKey", artifact.digest().usageKey(), true); + appendJsonField(manifest, "artifactKind", artifact.digest().artifactKind(), false); + appendJsonField( + manifest, "immutableObjectKey", artifact.digest().immutableObjectKey(), false); + appendJsonField(manifest, "contentDigest", artifact.digest().contentDigest(), false); + appendJsonField(manifest, "contentType", artifact.digest().contentType(), false); + manifest + .append(",\"artifactSchemaVersion\":") + .append(artifact.digest().artifactSchemaVersion()); + appendJsonField(manifest, "producerService", "game-design-service", false); + appendJsonField(manifest, "versionId", artifact.manifestVersionId().toString(), false); + appendJsonField(manifest, "url", artifact.url(), false); + manifest.append('}'); + } + manifest.append("}}"); + return manifest.toString().getBytes(StandardCharsets.UTF_8); + } + + private static void appendJsonField( + StringBuilder json, String key, String value, boolean firstInObject) { + if (!firstInObject) { + json.append(','); + } + appendJsonString(json, key); + json.append(':'); + appendJsonString(json, value); + } + + private static void appendJsonString(StringBuilder json, String value) { + json.append('"'); + for (int offset = 0; offset < value.length(); ) { + int codePoint = value.codePointAt(offset); + switch (codePoint) { + case '"' -> json.append("\\\""); + case '\\' -> json.append("\\\\"); + case '\b' -> json.append("\\b"); + case '\f' -> json.append("\\f"); + case '\n' -> json.append("\\n"); + case '\r' -> json.append("\\r"); + case '\t' -> json.append("\\t"); + default -> { + if (codePoint < 0x20) { + json.append("\\u00"); + json.append(Character.forDigit((codePoint >>> 4) & 0xf, 16)); + json.append(Character.forDigit(codePoint & 0xf, 16)); + } else { + json.appendCodePoint(codePoint); + } + } + } + offset += Character.charCount(codePoint); + } + json.append('"'); + } + + private String requireApprovedPublicBaseUrl() { + String configured = properties.getPublicBaseUrl(); + try { + if (configured == null || configured.isBlank()) { + throw new IllegalArgumentException("missing public base URL"); + } + URI uri = new URI(configured); + String path = uri.getRawPath(); + if (!uri.isAbsolute() + || !"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() == 0 + || uri.getPort() > 65535 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !("/assets".equals(path) || "/assets/".equals(path))) { + throw new IllegalArgumentException( + "public base URL must be an approved HTTPS /assets origin"); + } + rejectPrivateEndpointAlias(uri); + return "https://" + uri.getRawAuthority() + "/assets"; + } catch (URISyntaxException | IllegalArgumentException exception) { + throw new IllegalStateException(PUBLIC_BASE_URL_INVALID, exception); + } + } + + private void rejectPrivateEndpointAlias(URI publicUri) { + String endpoint = properties.getEndpoint(); + if (endpoint == null || endpoint.isBlank()) { + return; + } + try { + URI privateUri = new URI(endpoint); + if (normalizeHost(publicUri.getHost()).equals(normalizeHost(privateUri.getHost()))) { + throw new IllegalArgumentException( + "public base URL aliases the private object-store endpoint"); + } + } catch (URISyntaxException exception) { + throw new IllegalArgumentException("invalid private object-store endpoint", exception); + } + } + + private static String normalizeHost(String host) { + if (host == null) { + return ""; + } + String normalized = host.toLowerCase(java.util.Locale.ROOT); + return normalized.endsWith(".") ? normalized.substring(0, normalized.length() - 1) : normalized; + } + + private void writeAndVerifyImmutableObject(String key, byte[] bytes, String contentType) { + RuntimeException putFailure = null; + try { s3Client.putObject( PutObjectRequest.builder() .bucket(properties.getBucket()) .key(key) - .contentType(asset.contentType()) + .contentType(contentType) + .contentLength((long) bytes.length) + .ifNoneMatch("*") .build(), - RequestBody.fromBytes(asset.data())); - String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + key; - manifest.put(asset.fileName(), url); - requiredManifestAssetKeys.add(asset.fileName()); + RequestBody.fromBytes(bytes)); + } catch (RuntimeException exception) { + putFailure = exception; } + try { - String manifestJson = objectMapper.writeValueAsString(manifest); - s3Client.putObject( - PutObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + MANIFEST_OBJECT_KEY) - .contentType("application/json") - .build(), - RequestBody.fromString(manifestJson, StandardCharsets.UTF_8)); - requiredManifestAssetKeys.add(MANIFEST_OBJECT_KEY); - return new ExportedAssetManifest( - sha256(manifestJson), List.copyOf(requiredManifestAssetKeys)); - } catch (Exception e) { - throw new IllegalStateException("Failed to write manifest", e); - } - } - - private VersionResolution resolveVersionScope(String tenantId, int versionNumber) { - Version version = - versionRepository - .findByTenantIdAndVersionNumber(tenantId, versionNumber) - .orElseThrow(() -> new IllegalArgumentException(REPAIR_VERSION_SCOPE_UNAVAILABLE)); - return new VersionResolution( - new VersionScope(tenantId, version.getId(), versionNumber), version.getVersionState()); - } - - private FrozenAssetSnapshot resolveSnapshot( - VersionScope scope, VersionLifecycleState versionState) { - FrozenAssetSnapshot existing = frozenSnapshots.get(scope); - if (existing != null) { - return existing; - } - if (versionState == VersionLifecycleState.PUBLISHED - || versionState == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - FrozenAssetSnapshot candidate = freeze(repository.findByTenantId(scope.tenantId())); - synchronized (frozenSnapshots) { - FrozenAssetSnapshot concurrent = frozenSnapshots.get(scope); - if (concurrent != null) { - return concurrent; - } - VersionResolution current = resolveVersionScope(scope.tenantId(), scope.versionNumber()); - if (!scope.equals(current.scope()) - || current.versionState() == VersionLifecycleState.PUBLISHED - || current.versionState() == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - if (frozenSnapshots.size() >= properties.getFrozenSnapshotCacheMaxEntries()) { - throw new IllegalStateException(EXPORT_SNAPSHOT_CAPACITY); - } - frozenSnapshots.put(scope, candidate); - return candidate; - } - } - - private FrozenAssetSnapshot freeze(List assets) { - Map frozenByUsageKey = new LinkedHashMap<>(); - for (GameAsset asset : assets) { - byte[] data = asset.getData(); - FrozenAsset frozen = - new FrozenAsset( - asset.getId(), asset.getFileName(), asset.getContentType(), data, sha256(data)); - if (MANIFEST_OBJECT_KEY.equals(asset.getFileName()) - || frozenByUsageKey.putIfAbsent(asset.getFileName(), frozen) != null) { - throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + verifyReadback(key, bytes, contentType); + } catch (ImmutableObjectConflictException conflict) { + if (putFailure != null) { + conflict.addSuppressed(putFailure); } + throw conflict; + } catch (RuntimeException readFailure) { + AssetExportOutcomePendingException pending = + new AssetExportOutcomePendingException( + "exact object readback is unavailable for " + key, readFailure); + if (putFailure != null) { + pending.addSuppressed(putFailure); + } + throw pending; } - return new FrozenAssetSnapshot(List.copyOf(frozenByUsageKey.values())); } - @Override - @Timed("gamedesign.asset.delete") - public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { - String prefix = tenantId + "/" + version + "/"; - for (String assetKey : new LinkedHashSet<>(manifestAssetKeys)) { - s3Client.deleteObject( - DeleteObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + assetKey) - .build()); + private void verifyReadback(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = + s3Client.getObjectAsBytes( + GetObjectRequest.builder().bucket(properties.getBucket()).key(key).build()); + byte[] actualBytes = response.asByteArray(); + Long actualSize = response.response().contentLength(); + String actualContentType = response.response().contentType(); + if (actualSize == null + || actualSize.longValue() != expectedBytes.length + || !Objects.equals(expectedContentType, actualContentType) + || !Arrays.equals(expectedBytes, actualBytes) + || !sha256Hex(expectedBytes).equals(sha256Hex(actualBytes))) { + throw new ImmutableObjectConflictException(key); } } - private String sha256(String value) { - return sha256(value.getBytes(StandardCharsets.UTF_8)); + @Override + @Timed("gamedesign.asset.delete") + public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { + throw new IllegalStateException( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects"); } - private String sha256(byte[] value) { + private static String sha256Hex(byte[] value) { try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte current : hash) { + result.append(Character.forDigit((current >>> 4) & 0xf, 16)); + result.append(Character.forDigit(current & 0xf, 16)); } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 unavailable", ex); + return result.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); } } - private record VersionResolution(VersionScope scope, VersionLifecycleState versionState) {} - - private record VersionScope(String tenantId, Long versionId, int versionNumber) {} + private record PreparedArtifact( + PublishedArtifactDigest digest, byte[] bytes, UUID manifestVersionId, String url) { + private PreparedArtifact { + bytes = bytes.clone(); + } - private record FrozenAssetSnapshot(List assets) { - private FrozenAssetSnapshot { - assets = List.copyOf(assets); + @Override + public byte[] bytes() { + return bytes.clone(); } } - private record FrozenAsset( - Long sourceAssetId, String fileName, String contentType, byte[] data, String contentHash) { - private FrozenAsset { - data = data == null ? null : data.clone(); - } + private static final class ImmutableObjectConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; - @Override - public byte[] data() { - return data == null ? null : data.clone(); + private ImmutableObjectConflictException(String key) { + super( + IMMUTABLE_OBJECT_CONFLICT + ": existing object does not match requested bytes at " + key); } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java new file mode 100644 index 0000000000..5bc425144a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +/** A deterministic launch business denial whose exact request outcome is stored by the owner. */ +final class FrozenLaunchDescriptorDenialException extends IllegalArgumentException { + private final String failureCode; + + static FrozenLaunchDescriptorDenialException create(String failureCode, String detail) { + return new FrozenLaunchDescriptorDenialException(failureCode, failureCode + ": " + detail); + } + + private FrozenLaunchDescriptorDenialException(String failureCode, String message) { + super(message); + this.failureCode = failureCode; + } + + static FrozenLaunchDescriptorDenialException fromStored(String failureCode, String message) { + return new FrozenLaunchDescriptorDenialException(failureCode, message); + } + + String failureCode() { + return failureCode; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 24087faa9f..efc0fd705b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -8,8 +8,11 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; @@ -52,6 +55,8 @@ import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsRequest; import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsResponse; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; @@ -117,6 +122,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -133,6 +139,9 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -702,10 +711,11 @@ public void getPublishedReleaseBundle( GetPublishedReleaseBundleResponse.Builder builder = GetPublishedReleaseBundleResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); + requirePublishedReleaseBundleReadAccess(); PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + requireCanonicalReleaseIdentityPair(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( @@ -745,7 +755,34 @@ public void getPublishedReleaseBundle( .setScriptPatchVersion( bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) .setPublishedAt(bundle.publishedAt().toString()) + .setPublishedReleaseBundleRef( + bundle.publishedReleaseBundleRef() == null + ? "" + : bundle.publishedReleaseBundleRef()) + .setCanonicalTenantId( + bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) + .setCanonicalVersionId( + bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) + .addAllArtifactDigests( + bundle.artifactDigests() == null + ? List.of() + : bundle.artifactDigests().stream() + .map( + digest -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest + .newBuilder() + .setUsageKey(digest.usageKey()) + .setArtifactKind(digest.artifactKind()) + .setImmutableObjectKey(digest.immutableObjectKey()) + .setContentDigest(digest.contentDigest()) + .setContentType(digest.contentType()) + .setArtifactSchemaVersion(digest.artifactSchemaVersion()) + .build()) + .toList()) .build()); + if (bundle.manifestSchemaVersion() != null) { + builder.getBundleBuilder().setManifestSchemaVersion(bundle.manifestSchemaVersion()); + } } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -857,36 +894,38 @@ public void resolveLaunchDescriptor( StreamObserver responseObserver) { ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), request.hasRequestedScriptPatchVersion() ? request.getRequestedScriptPatchVersion() : null, + request.hasSourceVersionId(), request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), request.hasRequestedRuntimeFlagsJson() ? request.getRequestedRuntimeFlagsJson() : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -909,7 +948,15 @@ public void resolveLaunchDescriptor( meterRegistry, logger, "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (IllegalStateException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); } catch (Exception ex) { builder.setError( @@ -919,6 +966,51 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -1946,6 +2038,95 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var 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 net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { + UUID canonicalTenantId = bundle.canonicalTenantId(); + UUID canonicalVersionId = bundle.canonicalVersionId(); + if (canonicalTenantId == null && canonicalVersionId == null) { + return; + } + UUID nilUuid = new UUID(0L, 0L); + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(nilUuid) + || canonicalVersionId.equals(nilUuid)) { + throw new IllegalArgumentException("published release canonical identity pair is invalid"); + } + } + private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsupported) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -1968,6 +2149,14 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") + || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") + || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } @@ -2055,6 +2244,46 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requirePublishedReleaseBundleReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("automation-scripting-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Automation workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 5b2c3139bb..f295ad77fc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -1,20 +1,23 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -22,249 +25,666 @@ import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import tools.jackson.core.exc.StreamReadException; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final Logger logger = LoggingUtil.getLogger(LaunchDescriptorServiceImpl.class); - + private static final UUID NIL_UUID = new UUID(0L, 0L); private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; private final TemplateRemapSetService templateRemapSetService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final ObjectMapper objectMapper; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @Override - @Transactional + @Transactional(noRollbackFor = FrozenLaunchDescriptorDenialException.class) @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + AuthoredWorldLaunchDescriptorEvidence.Request request) { + requireConfiguredNamespace(request.targetNamespace()); + launchDescriptorRepository.lockBoundRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + String requestJson = writeJson(request); + + Optional stored = + launchDescriptorRepository.findBoundByRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + if (stored.isPresent()) { + LaunchDescriptor descriptor = stored.orElseThrow(); + requireStoredRequestMatches(descriptor, request, requestJson); + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + throwStoredFailure( + descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, requestJson, sourceJson); + } + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (launchDescriptorRepository + .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) + .isPresent()) { throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId is required"); + "LAUNCH_DESCRIPTOR_CONFLICT: retained private-owner request history is unbound or bound to another canonical identity"); + } + + try { + return resolveNewLaunchDescriptor(request, source, requestJson, sourceJson); + } catch (FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); + LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); + throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throw new IllegalStateException("Persisted deterministic launch denial was not returned"); } + } + + private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { GameTemplateLaunchConfigView template = gameTemplateRepository - .findLaunchConfigByTenantIdAndId(tenantId, gameTemplateId) + .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) + .filter(row -> row.getId() == request.gameTemplateId()) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: game template not found")); - String requestHash = - hashRequest( - tenantId, - gameTemplateId, - controlPlaneRequestId, - requestedScriptPatchVersion, - sourceVersionId, - targetVersionId, - requestedRuntimeFlagsJson); - var existing = - launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - tenantId, gameTemplateId, controlPlaneRequestId); - if (existing.isPresent()) { - if (!existing.get().getRequestHash().equals(requestHash)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId already resolved with different inputs"); - } - return toDto(existing.get()); - } + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "template is not owned by the source game")); if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw new IllegalArgumentException( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + throw denial( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); } - Long resolvedVersionId = - targetVersionId != null ? targetVersionId : template.getDefaultVersionId(); - if (resolvedVersionId == null || resolvedVersionId <= 0L) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template defaultVersionId is required"); + Long versionId = + request.targetVersionIdPresent() + ? request.targetVersionId() + : template.getDefaultVersionId(); + if (versionId == null || versionId <= 0) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "template defaultVersionId is required"); } VersionDto version = versionRepository - .findById(resolvedVersionId) - .filter(found -> found.getTenantId().equals(tenantId)) + .findById(versionId) + .filter(row -> row.getId().equals(versionId)) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .map( - found -> + row -> new VersionDto( - found.getId(), - found.getTenantId(), - found.getVersionNumber(), - found.getVersionState(), - found.getVersionStateEpoch(), - found.getScriptPatchVersion(), - found.getBaseVersionId(), - found.isScriptOnly(), - found.getNotes(), - found.getCreatedAt(), - found.getUpdatedAt())) + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: target version not found")); + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); if (version.versionState() != VersionLifecycleState.PUBLISHED && version.versionState() != VersionLifecycleState.ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); + throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); } - String resolvedScriptPatchVersion = - resolveScriptPatchVersion(template, requestedScriptPatchVersion, version); - String resolvedRuntimeFlagsJson = resolveRuntimeFlagsJson(template, requestedRuntimeFlagsJson); + requireReadyScriptPatch( + request.requestedScriptPatchVersionPresent() + ? request.requestedScriptPatchVersion() + : null); + requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); + requireReadyScriptPatch(version.scriptPatchVersion()); + String scriptPatch = resolveScriptPatchVersion(template, request, version); + String runtimeFlags = resolveRuntimeFlagsJson(template, request); + String remapSetId = null; - if (sourceVersionId != null && !sourceVersionId.equals(resolvedVersionId)) { - TemplateRemapSetDto remapSet = + if (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { + TemplateRemapSetDto remap = templateRemapSetService - .findApprovedTemplateRemapSet(tenantId, sourceVersionId, resolvedVersionId) + .findApprovedTemplateRemapSet( + source.sourceGameTenantKey(), request.sourceVersionId(), versionId) .orElseThrow( () -> - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - remapSetId = remapSet.remapSetId(); + denial( + "LAUNCH_REMAP_REQUIRED", + "replacement-instance launch requires an approved remapSetId")); + remapSetId = remap.remapSetId(); + } + PublishedReleaseBundleDto bundle = + requirePublishedReleaseBundle(source.sourceGameTenantKey(), versionId); + if (!source.sourceGameTenantKey().equals(bundle.tenantId()) + || !Objects.equals(bundle.versionId(), versionId)) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); + } + try { + PublishedReleaseBundleContract.requireSupportedSchemaForLaunchDescriptor(bundle); + } catch (IllegalArgumentException invalid) { + if (invalid.getMessage() != null + && invalid + .getMessage() + .startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED + ":")) { + throw denial( + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, + "unsupported published release bundle attestation schema " + + bundle.attestationSchemaVersion()); + } + throw invalid; } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + if (bundle.publishedReleaseBundleRef() == null + || bundle.publishedReleaseBundleRef().isBlank()) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "published release bundle has no persisted opaque reference"); + } + + String descriptorId = "ld-" + UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptorId, + versionId, + scriptPatch != null, + scriptPatch, + runtimeFlags, + bundle.generationConfigRevision(), + version.versionStateEpoch(), + bundle.id(), + bundle.publishedReleaseBundleRef(), + remapSetId != null, + remapSetId); LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId("ld-" + UUID.randomUUID()); - descriptor.setTenantId(tenantId); - descriptor.setGameTemplateId(gameTemplateId); - descriptor.setControlPlaneRequestId(controlPlaneRequestId); - descriptor.setRequestHash(requestHash); - descriptor.setVersionId(resolvedVersionId); - descriptor.setScriptPatchVersion(resolvedScriptPatchVersion); - descriptor.setRuntimeFlagsJson(resolvedRuntimeFlagsJson); + descriptor.setLaunchDescriptorId(descriptorId); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(versionId); + descriptor.setScriptPatchVersion(scriptPatch); + descriptor.setRuntimeFlagsJson(runtimeFlags); descriptor.setGenerationConfigRevision(bundle.generationConfigRevision()); descriptor.setVersionStateEpoch(version.versionStateEpoch()); descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef( - releaseBundleRef(tenantId, bundle.id(), resolvedVersionId)); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); descriptor.setRemapSetId(remapSetId); - logger.info( - "Resolved launch descriptor tenant={} template={} controlPlaneRequestId={} version={} remapSetId={}", - tenantId, - gameTemplateId, - controlPlaneRequestId, - resolvedVersionId, - remapSetId); - return toDto(launchDescriptorRepository.save(descriptor)); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); + } + + @Override + @Transactional(readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.read") + public ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + AuthoredWorldSourceEvidence source = readExactSource(storedRequest); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + @Override + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.readOwnerSnapshot") + public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + requireOwnerSnapshot(); + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + var sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + storedRequest.authoredWorldSourceOperationId(), + storedRequest.authoredWorldSourceEvidenceDigest(), + Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireExactSource(storedRequest, source); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + private DescriptorReadContext findExactSuccessfulDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Canonical nonnil read request ID is required"); + } + requireConfiguredNamespace(workloadNamespace); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || !GameTenantCreationDigest.isDigest(expectedRequestDigest) + || !GameTenantCreationDigest.isDigest(expectedResultDigest)) { + throw new IllegalArgumentException("Exact descriptor read selector and digests are required"); + } + LaunchDescriptor descriptor = + launchDescriptorRepository + .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) + .orElseThrow( + () -> + new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); + } + if (descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: retained descriptor history has no authored-world binding"); + } + if (!worldSlug.equals(descriptor.getWorldSlug()) + || !canonicalTenantId.toString().equals(descriptor.getCanonicalTenantId()) + || !expectedRequestDigest.equals(descriptor.getRequestDigest()) + || !expectedResultDigest.equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match"); + } + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = + readRequest(descriptor.getOriginalRequestJson()); + return new DescriptorReadContext(descriptor, storedRequest); + } + + private AuthoredWorldSourceEvidence readExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + AuthoredWorldSourceEvidence source = + authoredWorldSourceRepository + .read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + requireExactSource(request, source); + return source; + } + + private void requireExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.authoredWorldSourceOperationId().equals(source.operationId()) + || !request.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); + } + } + + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Launch descriptor snapshot read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private record DescriptorReadContext( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) {} + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getFailureCode() != null + || descriptor.getFailureMessage() != null + || descriptor.getDescriptorSchemaVersion() == null + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(denial.failureCode()); + descriptor.setFailureMessage(denial.getMessage()); + return descriptor; + } + + private void requireStoredRequestMatches( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson) { + if (!workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input"); + } + } + + private void throwStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson, + String sourceGameTenantKey) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !sourceGameTenantKey.equals(descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !isPersistableFailureCode(descriptor.getFailureCode()) + || descriptor.getFailureMessage() == null + || descriptor.getFailureMessage().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored failure is not the exact immutable request outcome"); + } + throw FrozenLaunchDescriptorDenialException.fromStored( + descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private boolean isPersistableFailureCode(String failureCode) { + return switch (failureCode == null ? "" : failureCode) { + case "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", + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED -> + true; + default -> false; + }; + } + + private static FrozenLaunchDescriptorDenialException denial(String code, String detail) { + return FrozenLaunchDescriptorDenialException.create(code, detail); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request readRequest(String json) { + if (json == null) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_UNBOUND: original request is missing"); + } + try { + AuthoredWorldLaunchDescriptorEvidence.Request request = + objectMapper.readValue(json, AuthoredWorldLaunchDescriptorEvidence.Request.class); + if (!writeJson(request).equals(json)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is not the closed owner encoding"); + } + return request; + } catch (Exception exception) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is unreadable", exception); + } + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException( + "Launch descriptor evidence could not be serialized", exception); + } + } + + private void requireConfiguredNamespace(String requestNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(requestNamespace)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NAMESPACE_MISMATCH: configured workload namespace is required"); + } } private String resolveScriptPatchVersion( GameTemplateLaunchConfigView template, - String requestedScriptPatchVersion, + AuthoredWorldLaunchDescriptorEvidence.Request request, VersionDto version) { String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = normalizeBlank(requestedScriptPatchVersion); + String requested = + request.requestedScriptPatchVersionPresent() + ? normalizeBlank(request.requestedScriptPatchVersion()) + : null; if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_OVERRIDE_CONFLICT: requested script patch conflicts with template default"); + throw denial( + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "requested script patch conflicts with template default"); } String resolved = requested != null ? requested : templateDefault; if (resolved != null && version.scriptPatchVersion() != null && !version.scriptPatchVersion().isBlank() && !version.scriptPatchVersion().equals(resolved)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_NOT_READY: requested script patch is not published for the resolved version"); + throw denial( + "SCRIPT_PATCH_NOT_READY", + "requested script patch is not published for the resolved version"); } return resolved; } private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, String requestedRuntimeFlagsJson) { + GameTemplateLaunchConfigView template, + AuthoredWorldLaunchDescriptorEvidence.Request request) { String templateFlags = normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null ? "{}" : template.getDefaultRuntimeFlagsJson(); - String requested = normalizeBlank(requestedRuntimeFlagsJson); + String requested = + request.requestedRuntimeFlagsJsonPresent() + ? normalizeBlank(request.requestedRuntimeFlagsJson()) + : null; if (requested == null) { return templateFlags; } if (!"{}".equals(templateFlags)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template-owned runtime flags cannot be overridden"); + throw denial( + "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); } return requested; } - private net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto - requirePublishedReleaseBundle(String tenantId, long resolvedVersionId) { - try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + private void requireReadyScriptPatch(String scriptPatchVersion) { + if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { + throw denial( + "SCRIPT_PATCH_NOT_READY", + "exact published-for-base and Automation READY evidence is unavailable"); } } - private ResolvedLaunchDescriptorDto toDto(LaunchDescriptor descriptor) { - return new ResolvedLaunchDescriptorDto( - descriptor.getLaunchDescriptorId(), - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId()); - } - - private String hashRequest( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - Map request = new LinkedHashMap<>(); - request.put("tenantId", tenantId); - request.put("gameTemplateId", gameTemplateId); - request.put("controlPlaneRequestId", controlPlaneRequestId); - request.put("requestedScriptPatchVersion", normalizeBlank(requestedScriptPatchVersion)); - request.put("sourceVersionId", sourceVersionId); - request.put("targetVersionId", targetVersionId); - request.put("requestedRuntimeFlagsJson", normalizeBlank(requestedRuntimeFlagsJson)); + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { try { - return sha256(objectMapper.writeValueAsString(request)); - } catch (StreamReadException | tools.jackson.databind.DatabindException ex) { - throw new IllegalStateException("failed to hash launch descriptor request", ex); - } - } - - private String releaseBundleRef(String tenantId, long bundleId, long versionId) { - return "prb:" + tenantId + ":" + versionId + ":" + bundleId; - } - - private String sha256(String value) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8)); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("sha-256 unavailable", ex); + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); } } - private String normalizeBlank(String value) { + private static String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 61800e105d..d4bf88cf3e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -9,13 +10,17 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -29,15 +34,19 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundle private final PublishedReleaseBundleRepository repository; private final RevisionRepository revisionRepository; + private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( PublishedReleaseBundleRepository repository, RevisionRepository revisionRepository, + VersionRepository versionRepository, ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); this.revisionRepository = Objects.requireNonNull(revisionRepository, "revisionRepository must not be null"); + this.versionRepository = + Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } @@ -49,38 +58,124 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + null); + } + + @Override + @Transactional + public PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); Objects.requireNonNull(participantDigests, "participantDigests must not be null"); - repository - .findByTenantIdAndVersionId(version.tenantId(), version.id()) - .ifPresent( - ignored -> { - throw new IllegalStateException("published release bundle already exists"); - }); + Optional existing = + repository.findByTenantIdAndVersionId(version.tenantId(), version.id()); + if (existing.isPresent() && worldEvidence == null) { + throw new IllegalStateException("published release bundle already exists"); + } + if (existing.isPresent()) { + PublishedReleaseBundleDto stored = toDto(existing.orElseThrow()); + PublishedReleaseBundleContract.requireExactSelectorRetry( + stored, + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + List originalCommandDefinitions = + repository.requireSelectedCommandDefinitions( + stored.tenantId(), + stored.versionId(), + stored.publishWorkflowId(), + stored.worldPublishedStartLocationEvidence()); + if (!stored.commandDefinitions().equals(originalCommandDefinitions)) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: stored command definitions differ from the original source capture"); + } + return stored; + } + var identitySource = + versionRepository + .findByTenantIdAndId(version.tenantId(), version.id()) + .orElseThrow( + () -> + new IllegalStateException( + "published release canonical identity source missing")); + UUID canonicalTenantId = identitySource.getCanonicalTenantId(); + UUID canonicalVersionId = identitySource.getCanonicalVersionId(); + if (!version.id().equals(identitySource.getId()) + || !version.tenantId().equals(identitySource.getTenantId()) + || !isCanonicalNonNilUuid(canonicalTenantId) + || !isCanonicalNonNilUuid(canonicalVersionId)) { + throw new IllegalStateException("published release canonical identity source is invalid"); + } PublishedReleaseBundle entity = new PublishedReleaseBundle(); entity.setTenantId(version.tenantId()); entity.setVersionId(version.id()); + entity.setCanonicalTenantId(canonicalTenantId); + entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( - PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION); + worldEvidence == null + ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION + : PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + entity.setWorldPublishedStartLocationEvidenceJson( + worldEvidence == null + ? null + : new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); entity.setPublishWorkflowId(publishWorkflowId); entity.setManifestHash(exportedManifest.manifestHash()); + entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); + entity.setArtifactDigestsJson( + objectMapper.writeValueAsString(exportedManifest.artifactDigests())); entity.setGenerationConfigRevision(generationConfigRevision); entity.setRequiredManifestAssetKeysJson( serializeKeys(exportedManifest.requiredManifestAssetKeys())); entity.setParticipantDigestsJson(serializeParticipantDigests(participantDigests)); List commandDefinitions = - revisionRepository - .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - version.tenantId(), version.id(), "COMMAND_DEFINITION") - .stream() - .map(revision -> revision.getData()) - .toList(); + worldEvidence == null + ? revisionRepository + .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + version.tenantId(), version.id(), "COMMAND_DEFINITION") + .stream() + .map(revision -> revision.getData()) + .toList() + : repository.requireSelectedCommandDefinitions( + version.tenantId(), version.id(), publishWorkflowId, worldEvidence); validateDistinctCommandDefinitions(commandDefinitions); entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); entity.setScriptOnly(version.scriptOnly()); entity.setScriptPatchVersion(version.scriptPatchVersion()); + if (worldEvidence != null) toDto(entity); return toDto(repository.save(entity)); } @@ -99,21 +194,48 @@ public Optional findPublishedReleaseBundle( } private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { - return new PublishedReleaseBundleDto( - entity.getId(), - entity.getTenantId(), - entity.getVersionId(), - entity.getVersionNumber(), - entity.getAttestationSchemaVersion(), - entity.getPublishWorkflowId(), - entity.getManifestHash(), - deserializeKeys(entity.getRequiredManifestAssetKeysJson()), - deserializeParticipantDigests(entity.getParticipantDigestsJson()), - deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), - entity.getGenerationConfigRevision(), - entity.isScriptOnly(), - entity.getScriptPatchVersion(), - entity.getPublishedAt()); + PublishedReleaseBundleDto dto = + new PublishedReleaseBundleDto( + entity.getId(), + entity.getTenantId(), + entity.getVersionId(), + entity.getVersionNumber(), + entity.getAttestationSchemaVersion(), + entity.getPublishWorkflowId(), + entity.getManifestHash(), + deserializeKeys(entity.getRequiredManifestAssetKeysJson()), + deserializeParticipantDigests(entity.getParticipantDigestsJson()), + deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), + entity.getGenerationConfigRevision(), + entity.isScriptOnly(), + entity.getScriptPatchVersion(), + entity.getPublishedAt(), + entity.getCanonicalTenantId(), + entity.getCanonicalVersionId(), + entity.getPublishedReleaseBundleRef(), + entity.getManifestSchemaVersion(), + entity.getArtifactDigestsJson() == null + ? null + : objectMapper.readValue( + entity.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)), + entity.getWorldPublishedStartLocationEvidenceJson() == null + ? null + : WorldPublishedStartLocationEvidence.fromStored( + entity + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8))); + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + dto.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSelectorBinding(dto); + } + return dto; + } + + private boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); } private String serializeKeys(List keys) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index e75f581c76..f5dcf8a99e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; @@ -169,6 +170,9 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + } catch (AssetExportOutcomePendingException ex) { + throw pendingReconciliation( + "asset export outcome is pending; retry exact publish request", ex); } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } diff --git a/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql b/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql new file mode 100644 index 0000000000..90883b945b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql @@ -0,0 +1,249 @@ +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_source_delivery_source UNIQUE ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +CREATE TABLE game_design_authored_world_source_deliveries ( + source_operation_id UUID PRIMARY KEY, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_schema_version INTEGER NOT NULL CHECK (intake_schema_version = 1), + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + world_operation_id UUID, + world_request_digest VARCHAR(71), + world_receipt_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + acknowledged_at TIMESTAMPTZ, + CONSTRAINT uq_gd_authored_world_source_delivery_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT fk_gd_authored_world_source_delivery_source FOREIGN KEY ( + source_operation_id, + source_schema_version, + target_namespace, + registration_request_id, + source_request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ), + CONSTRAINT chk_gd_authored_world_source_delivery_fresh CHECK ( + provenance_kind = 'NEW_GAME_ROW' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_ids CHECK ( + source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_game_row_id > 0 + ), + CONSTRAINT chk_gd_authored_world_source_delivery_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_digests CHECK ( + source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (world_operation_id IS NULL + AND world_request_digest IS NULL + AND world_receipt_digest IS NULL + AND acknowledged_at IS NULL) + OR + (world_operation_id IS NOT NULL + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_request_digest IS NOT NULL + AND world_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_receipt_digest IS NOT NULL + AND world_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + ), + CONSTRAINT chk_gd_authored_world_source_delivery_slugs CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_world_source_delivery() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.world_operation_id IS NOT NULL + OR NEW.world_request_digest IS NOT NULL + OR NEW.world_receipt_digest IS NOT NULL + OR NEW.acknowledged_at IS NOT NULL THEN + RAISE EXCEPTION 'New Game Design authored-world delivery cannot start acknowledged' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = o.target_namespace + AND b.canonical_tenant_id = o.canonical_tenant_id + AND b.tenant_slug = o.tenant_slug + AND b.source_game_row_id = o.source_game_row_id + AND b.source_game_tenant_key = o.source_game_tenant_key + AND b.provenance_kind = o.provenance_kind + JOIN game g + ON g.id = o.source_game_row_id + AND g.tenant_id = o.source_game_tenant_key + AND g.canonical_tenant_id = o.canonical_tenant_id + AND g.tenant_identity_provenance_kind = o.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE o.operation_id = NEW.source_operation_id + AND o.schema_version = NEW.source_schema_version + AND o.target_namespace = NEW.target_namespace + AND o.registration_request_id = NEW.registration_request_id + AND o.request_digest = NEW.source_request_digest + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.world_slug = NEW.world_slug + AND o.world_display_name = NEW.world_display_name + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = 'NEW_GAME_ROW' + AND o.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world delivery has no exact fresh source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF ROW( + NEW.source_operation_id, + NEW.source_schema_version, + NEW.target_namespace, + NEW.registration_request_id, + NEW.source_request_digest, + NEW.canonical_tenant_id, + NEW.tenant_slug, + NEW.world_slug, + NEW.world_display_name, + NEW.source_game_row_id, + NEW.source_game_tenant_key, + NEW.provenance_kind, + NEW.source_evidence_digest, + NEW.intake_schema_version, + NEW.intake_request_id, + NEW.intake_request_digest, + NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.source_operation_id, + OLD.source_schema_version, + OLD.target_namespace, + OLD.registration_request_id, + OLD.source_request_digest, + OLD.canonical_tenant_id, + OLD.tenant_slug, + OLD.world_slug, + OLD.world_display_name, + OLD.source_game_row_id, + OLD.source_game_tenant_key, + OLD.provenance_kind, + OLD.source_evidence_digest, + OLD.intake_schema_version, + OLD.intake_request_id, + OLD.intake_request_digest, + OLD.created_at + ) THEN + RAISE EXCEPTION 'Game Design authored-world delivery claim cannot be rebound' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.world_operation_id IS NULL + AND OLD.world_request_digest IS NULL + AND OLD.world_receipt_digest IS NULL + AND OLD.acknowledged_at IS NULL + AND NEW.world_operation_id IS NOT NULL + AND NEW.world_request_digest IS NOT NULL + AND NEW.world_receipt_digest IS NOT NULL + AND NEW.acknowledged_at IS NOT NULL THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Game Design authored-world delivery acknowledgement is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_deliveries + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source_delivery(); + +CREATE FUNCTION reject_gd_authored_world_source_delivery_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_deliveries + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_source_delivery_truncate(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..20d222fff3 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,624 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +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 java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +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.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +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; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("40"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void pendingDeliveryPagesAreNamespaceBoundKeysetOrderedAndExcludeAcknowledgedClaims() { + Fixture fixture = fixture(null); + String otherNamespace = "other-authored-world-delivery-test"; + AuthoredWorldSourceEvidence firstNamespaceSource = + fixture.register( + NAMESPACE, + uuid("12121212-1212-4212-8212-121212121212"), + fixture.freshGame(), + "pending-tenant-one", + "pending-world-one"); + AuthoredWorldSourceEvidence secondNamespaceSource = + fixture.register( + NAMESPACE, + uuid("13131313-1313-4313-8313-131313131313"), + fixture.createFreshGame(), + "pending-tenant-two", + "pending-world-two"); + AuthoredWorldSourceEvidence otherNamespaceSource = + fixture.register( + otherNamespace, + uuid("14141414-1414-4414-8414-141414141414"), + fixture.freshGame(), + "other-pending-tenant", + "other-pending-world"); + + var firstPage = fixture.deliveryRepository().readPending(NAMESPACE, null, 1); + var secondPage = + fixture + .deliveryRepository() + .readPending(NAMESPACE, firstPage.get(0).request().intakeRequestId(), 1); + var otherNamespacePage = fixture.deliveryRepository().readPending(otherNamespace, null, 10); + + assertThat(firstPage).hasSize(1); + assertThat(secondPage).hasSize(1); + assertThat(firstPage.get(0).source().operationId()) + .isNotEqualTo(secondPage.get(0).source().operationId()); + assertThat( + List.of( + firstPage.get(0).source().operationId(), secondPage.get(0).source().operationId())) + .containsExactlyInAnyOrder( + firstNamespaceSource.operationId(), secondNamespaceSource.operationId()); + assertThat(otherNamespacePage) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo(otherNamespaceSource.operationId()); + + DeliveryClaim pending = firstPage.get(0); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("15151515-1515-4515-8515-151515151515"), 'a'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + + assertThat(acknowledged).isNotNull(); + assertThat(fixture.deliveryRepository().readPending(NAMESPACE, null, 10)) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo( + firstNamespaceSource.operationId().equals(pending.source().operationId()) + ? secondNamespaceSource.operationId() + : firstNamespaceSource.operationId()); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V41 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V41 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + return register(NAMESPACE, registrationRequestId, sourceGame, tenantSlug, worldSlug); + } + + AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + Game sourceGame, + String tenantSlug, + String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + Game createFreshGame() { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Additional Fresh Delivery Source"); + game.setDescription("A second isolated fresh tenant source for pending paging"); + return Objects.requireNonNull( + transactionTemplate.execute(status -> new GameRepository(dsl).save(game))); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4382f496c0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +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; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV28ToV29Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 1dbcec0d96..4b83a38f23 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1,30 +1,65 @@ package integration.net.firedevops.firemud.gamedesign.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.LocalDateTime; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +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; @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -33,6 +68,7 @@ "spring.profiles.active=test", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=launch-descriptor-test", "spring.grpc.server.port=0", "asset.store.endpoint=http://localhost:9000", "asset.store.bucket=test-bucket", @@ -42,9 +78,20 @@ }) @Import(NoGrpcServerTestConfiguration.class) class LaunchDescriptorServiceIntegrationTest { + private static final String NAMESPACE = "launch-descriptor-test"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final org.jooq.Table LAUNCH_DESCRIPTOR = + DSL.table(DSL.name("launch_descriptor")); + private static final org.jooq.Field LAUNCH_ROW_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field LAUNCH_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final org.jooq.Field LAUNCH_CANONICAL_TENANT = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field LAUNCH_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { @@ -53,51 +100,999 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameTemplateRepository gameTemplateRepository; @Autowired private VersionRepository versionRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + + @Test + void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange() { + Fixture fixture = fixture("cp-persisted"); + + ResolvedLaunchDescriptorDto original = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + String generationConfigRevision = fixture.bundle().getGenerationConfigRevision(); + assertThat(generationConfigRevision.length()).isGreaterThan(128); + assertThat(original.generationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat(original.gameTemplateId()).isEqualTo(fixture.template().getId()); + assertThat(original.versionId()).isEqualTo(fixture.version().getId()); + assertThat(original.versionStateEpoch()).isEqualTo(1L); + assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); + assertThat(original.publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId( + fixture.privateSourceTenantKey(), fixture.version().getId()) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(original.authoredWorldBinding()).isNotNull(); + assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) + .isEqualTo(fixture.source().operationId()); + assertThat(original.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) + .isEqualTo(fixture.source().evidenceDigest()); + assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); + + Version newDraft = new Version(); + newDraft.setTenantId(fixture.privateSourceTenantKey()); + newDraft.setVersionNumber(2); + newDraft.setVersionState(VersionLifecycleState.DRAFT); + newDraft.setVersionStateEpoch(1L); + newDraft.setNotes("new mutable template default"); + newDraft.setUpdatedAt(LocalDateTime.now()); + newDraft = versionRepository.save(newDraft); + fixture.template().setDefaultVersionId(newDraft.getId()); + gameTemplateRepository.save(fixture.template()); + fixture.version().setVersionState(VersionLifecycleState.RETIRED); + fixture.version().setVersionStateEpoch(2L); + versionRepository.save(fixture.version()); + + ResolvedLaunchDescriptorDto retry = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + + assertThat(retry).isEqualTo(original); + assertThat(retry.versionId()).isEqualTo(fixture.version().getId()); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(original.launchDescriptorId()); + assertThat(persisted.getRequestDigest()) + .isEqualTo(original.authoredWorldBinding().requestDigest()); + assertThat(persisted.getResultDigest()) + .isEqualTo(original.authoredWorldBinding().resultDigest()); + assertThat(persisted.getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + ResolvedLaunchDescriptorDto readback = + launchDescriptorService.getLaunchDescriptor( + UUID.randomUUID(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + assertThat(readback).isEqualTo(original); + } + + @Test + void concurrentExactRetriesPersistOneOriginalDescriptor() throws Exception { + Fixture fixture = fixture("cp-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + ResolvedLaunchDescriptorDto firstResult = first.get(20, TimeUnit.SECONDS); + ResolvedLaunchDescriptorDto secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(secondResult).isEqualTo(firstResult); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(firstResult.launchDescriptorId()); + assertThat(persisted.getResultDigest()) + .isEqualTo(firstResult.authoredWorldBinding().resultDigest()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries() + throws Exception { + Fixture fixture = fixture("cp-frozen-phase"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + + assertThatThrownBy(() -> launchDescriptorService.resolveLaunchDescriptor(fixture.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + + LaunchDescriptor failed = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(failed.getOutcomeStatus()).isEqualTo(LaunchDescriptor.OUTCOME_FAILED); + assertThat(failed.getFailureCode()).isEqualTo("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + assertThat(failed.getFailureMessage()) + .isEqualTo( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(failed.getOriginalRequestJson()).isNotBlank(); + assertThat(failed.getSourceEvidenceJson()).isNotBlank(); + assertThat(failed.getLaunchDescriptorId()).isNull(); + assertThat(failed.getGameTemplateId()).isNull(); + assertThat(failed.getVersionId()).isNull(); + assertThat(failed.getReleaseBundleId()).isNull(); + assertThat(failed.getResultDigest()).isNull(); + assertFailedShapeRejected(failed, "cp-frozen-null-schema", true); + assertFailedShapeRejected(failed, "cp-frozen-null-failure-code", false); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + gameTemplateRepository.save(fixture.template()); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> + launchDescriptorService.resolveLaunchDescriptor( + fixture.requestWithPatch("different-patch"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("control-plane request identity was reused with changed input"); + + ResolvedLaunchDescriptorDto freshAttempt = + launchDescriptorService.resolveLaunchDescriptor(fixture.request("cp-frozen-phase-fresh")); + assertThat(freshAttempt.versionId()).isEqualTo(fixture.version().getId()); + assertThat( + launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), "cp-frozen-phase-fresh") + .orElseThrow() + .getOutcomeStatus()) + .isEqualTo(LaunchDescriptor.OUTCOME_SUCCESS); + } + + @Test + void corruptFailureReadbackRollsBackTheOutcomeInsert() { + Fixture fixture = fixture("cp-corrupt-failure-readback"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + LaunchDescriptorRepository corruptingRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + LaunchDescriptor persisted = super.insertImmutable(descriptor); + persisted.setFailureCode("UNRECOGNIZED_FAILURE"); + return persisted; + } + }; + LaunchDescriptorServiceImpl corruptingService = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + corruptingRepository, + versionRepository, + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stored failure is not the exact immutable request outcome"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + } + + @Test + void concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome() throws Exception { + Fixture fixture = fixture("cp-mixed-candidates"); + CountDownLatch lockArrivals = new CountDownLatch(2); + CountDownLatch viewReached = new CountDownLatch(1); + CountDownLatch continueResolution = new CountDownLatch(1); + LaunchDescriptorRepository serializedRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public void lockBoundRequest(String targetNamespace, UUID tenantId, String requestId) { + lockArrivals.countDown(); + super.lockBoundRequest(targetNamespace, tenantId, requestId); + } + }; + LaunchDescriptorServiceImpl failureCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.LEGACY, + viewReached, + continueResolution); + LaunchDescriptorServiceImpl successCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.ENFORCED, + viewReached, + continueResolution); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> resolveCandidateInOwnerTransaction(failureCandidate, fixture, ready, start)); + Future second = + executor.submit( + () -> resolveCandidateInOwnerTransaction(successCandidate, fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(viewReached.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(lockArrivals.await(10, TimeUnit.SECONDS)).isTrue(); + continueResolution.countDown(); + + String firstResult = first.get(20, TimeUnit.SECONDS); + String secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + LaunchDescriptor stored = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(stored.getOutcomeStatus()) + .isEqualTo( + firstResult.startsWith("FAILED:") + ? LaunchDescriptor.OUTCOME_FAILED + : LaunchDescriptor.OUTCOME_SUCCESS); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + } finally { + continueResolution.countDown(); + start.countDown(); + executor.shutdownNow(); + } + } @Test - void resolvesLaunchDescriptorForJsonConfiguredTemplate() { + void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { + Fixture fixture = fixture("cp-rollback"); + AuthoredWorldLaunchDescriptorEvidence evidence = evidence(fixture, "ld-rollback-candidate"); + LaunchDescriptor candidate = entity(evidence, fixture); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> { + launchDescriptorRepository.insertImmutable(candidate); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + assertThat( + launchDescriptorRepository.findByPrivateRequest( + fixture.privateSourceTenantKey(), fixture.controlPlaneRequestId())) + .isEmpty(); + ResolvedLaunchDescriptorDto committed = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + assertThat(committed.authoredWorldBinding().requestDigest()) + .isEqualTo(evidence.requestDigest()); + } + + @Test + void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager isolatedTransactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate isolatedTransaction = new TransactionTemplate(isolatedTransactionManager); + + String privateTenantKey = privateTenantKey(); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Retained launch source"); + game.setDescription("Persisted V34 source fixture"); + Game persistedGame = + isolatedTransaction.execute(status -> new GameRepository(isolatedDsl).save(game)); + assertThat(persistedGame).isNotNull(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + seedPreV41AuthoredWorldSource( + isolatedDsl, + isolatedTransaction, + persistedGame, + UUID.randomUUID(), + "tenant-" + suffix, + "world-" + suffix, + "Retained World 🐉"); + assertThat(source).isNotNull(); + + Long versionId = + isolatedDsl + .resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 1) RETURNING id", + privateTenantKey) + .fetchOne(0, Long.class); + Long templateId = + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + privateTenantKey, + "Retained Template " + suffix) + .fetchOne(0, Long.class); + // Synthetic retained-row seed for storage compatibility only; not live publication proof. + Long bundleId = + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + privateTenantKey, + versionId, + "synthetic-retained-fixture-" + suffix, + "sha256:" + "d".repeat(64), + "gen-rev:" + suffix) + .fetchOne(0, Long.class); + if (bundleId == null) { + throw new IllegalStateException("Retained V34 release bundle insertion returned no identity"); + } + String requestId = "retained-cp-" + suffix; + String legacyDescriptorId = "ld-retained-" + suffix; + isolatedDsl.execute( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, control_plane_request_id, " + + "request_hash, version_id, runtime_flags_json, generation_config_revision, " + + "version_state_epoch, release_bundle_id, published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?)", + legacyDescriptorId, + privateTenantKey, + templateId, + requestId, + "legacy-request-hash-" + suffix, + versionId, + "gen-rev:" + suffix, + bundleId, + "legacy-release-ref-" + suffix); + Map retainedV34Snapshot = + legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); + Map retainedBundleSnapshot = + retainedReleaseBundleSnapshot(isolatedDsl, bundleId); + + migrate(dataSource, schema, null); + LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); + var retainedBundleReference = + isolatedDsl.fetchOne( + "SELECT published_release_bundle_ref FROM published_release_bundle WHERE id = ?", + bundleId); + if (retainedBundleReference == null) { + throw new IllegalStateException("Retained V34 release bundle reference row is missing"); + } + assertThat(retainedBundleReference.get("published_release_bundle_ref", String.class)).isNull(); + assertThat(retainedReleaseBundleSnapshot(isolatedDsl, bundleId)) + .isEqualTo(retainedBundleSnapshot); + assertThat( + new PublishedReleaseBundleRepository(isolatedDsl) + .findByTenantIdAndVersionId(privateTenantKey, versionId) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isNull(); + assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) + .isEqualTo(retainedV34Snapshot); + LaunchDescriptor before = + launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow(); + assertThat(before.getDescriptorSchemaVersion()).isNull(); + assertThat(before.getCanonicalTenantId()).isNull(); + assertThat(before.getRequestHash()).isEqualTo("legacy-request-hash-" + suffix); + + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + templateId, + false, + null, + false, + null, + false, + null, + false, + null); + LaunchDescriptorServiceImpl isolatedService = + new LaunchDescriptorServiceImpl( + Mockito.mock(GameTemplateRepository.class), + launchRepository, + Mockito.mock(VersionRepository.class), + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + new GameAuthoredWorldSourceRepository(isolatedDsl), + new ObjectMapper()); + ReflectionTestUtils.setField(isolatedService, "workloadNamespace", NAMESPACE); + + assertThatThrownBy(() -> isolatedService.resolveLaunchDescriptor(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("LAUNCH_DESCRIPTOR_CONFLICT") + .hasMessageContaining("unbound"); + assertThat( + launchRepository.findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), requestId)) + .isEmpty(); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", + "{\"changed\":true}", + before.getId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("launch descriptors are immutable"); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + } + + private Fixture fixture(String controlPlaneRequestId) { + String privateTenantKey = privateTenantKey(); + Game sourceGame = new Game(); + sourceGame.setTenantId(privateTenantKey); + sourceGame.setName("Launch Source " + UUID.randomUUID()); + sourceGame.setDescription("Persisted fresh Game Design tenant source"); + Game persistedGame = + new TransactionTemplate(transactionManager) + .execute(status -> gameRepository.save(sourceGame)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Launch World 🐉")); + assertThat(source).isNotNull(); + Version version = new Version(); - version.setTenantId("1"); + version.setTenantId(privateTenantKey); version.setVersionNumber(1); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(1L); - version.setNotes("integration test version"); + version.setNotes("synthetic release storage proof fixture"); version.setUpdatedAt(LocalDateTime.now()); version = versionRepository.save(version); GameTemplate template = new GameTemplate(); - template.setTenantId("1"); - template.setName("Integration Template"); - template.setDescription("launch descriptor integration template"); + template.setTenantId(privateTenantKey); + template.setName("Launch Template " + suffix); + template.setDescription("Persisted descriptor resolution fixture"); template.setConfig("{}"); template.setDefaultVersionId(version.getId()); template.setDefaultRuntimeFlagsJson("{}"); template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); template = gameTemplateRepository.save(template); + // This row exercises descriptor storage and resolution only; it is not live publication proof. PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId("1"); + bundle.setTenantId(privateTenantKey); bundle.setVersionId(version.getId()); bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("integration-seed"); - bundle.setManifestHash("integration-manifest"); - bundle.setGenerationConfigRevision("genrev:integration"); + bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); + bundle.setManifestHash("sha256:" + "e".repeat(64)); + bundle.setGenerationConfigRevision("gen-rev:" + suffix + ":" + "g".repeat(180)); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setScriptOnly(false); - publishedReleaseBundleRepository.save(bundle); + bundle = publishedReleaseBundleRepository.save(bundle); + + return new Fixture( + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + bundle); + } + + private void assertFailedShapeRejected( + LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { + assertThatThrownBy( + () -> + dsl.execute( + """ + INSERT INTO launch_descriptor ( + tenant_id, + control_plane_request_id, + request_hash, + descriptor_schema_version, + target_namespace, + canonical_tenant_id, + world_slug, + authored_world_source_operation_id, + authored_world_source_evidence_digest, + request_digest, + original_request_json, + source_evidence_json, + outcome_status, + failure_code, + failure_message) + VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, + CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) + """, + failed.getTenantId(), + controlPlaneRequestId, + failed.getRequestHash(), + nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), + failed.getTargetNamespace(), + failed.getCanonicalTenantId(), + failed.getWorldSlug(), + failed.getAuthoredWorldSourceOperationId(), + failed.getAuthoredWorldSourceEvidenceDigest(), + failed.getRequestDigest(), + failed.getOriginalRequestJson(), + failed.getSourceEvidenceJson(), + nullSchemaVersion ? failed.getFailureCode() : null, + failed.getFailureMessage())) + .isInstanceOf(DataIntegrityViolationException.class) + .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); + } + + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } + + private String resolveFailureAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + try { + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + return "unexpected success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + } + + private String resolveCandidateInOwnerTransaction( + LaunchDescriptorServiceImpl service, + Fixture fixture, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return new TransactionTemplate(transactionManager) + .execute( + status -> { + try { + return "SUCCESS:" + + service + .resolveLaunchDescriptor(fixture.request()) + .authoredWorldBinding() + .resultDigest(); + } catch (IllegalArgumentException exception) { + return "FAILED:" + exception.getMessage(); + } + }); + } + + private LaunchDescriptorServiceImpl candidateForPhase( + Fixture fixture, + LaunchDescriptorRepository repository, + TemplateReferencePhase phase, + CountDownLatch viewReached, + CountDownLatch continueResolution) { + GameTemplateRepository templateRepository = Mockito.mock(GameTemplateRepository.class); + GameTemplateLaunchConfigView view = Mockito.mock(GameTemplateLaunchConfigView.class); + Mockito.when(view.getId()).thenReturn(fixture.template().getId()); + Mockito.when(view.getTenantId()).thenReturn(fixture.privateSourceTenantKey()); + Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); + Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + Mockito.when(view.getTemplateReferencePhase()) + .thenAnswer( + invocation -> { + viewReached.countDown(); + await(continueResolution); + return phase; + }); + Mockito.when( + templateRepository.findLaunchConfigByTenantIdAndId( + fixture.privateSourceTenantKey(), fixture.template().getId())) + .thenReturn(java.util.Optional.of(view)); + LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + templateRepository, + repository, + versionRepository, + publishedReleaseBundleService, + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + return service; + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for descriptor retry race"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for descriptor retry race", exception); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence(Fixture fixture, String descriptorId) { + return AuthoredWorldLaunchDescriptorEvidence.create( + fixture.request(), + descriptorId, + fixture.version().getId(), + false, + null, + "{}", + fixture.bundle().getGenerationConfigRevision(), + fixture.version().getVersionStateEpoch(), + fixture.bundle().getId(), + "release-bundle:" + + fixture.canonicalTenantId() + + ":" + + fixture.version().getId() + + ":" + + fixture.bundle().getId(), + false, + null); + } + + private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, Fixture fixture) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(fixture.privateSourceTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(evidence.scriptPatchVersion()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(evidence.remapSetId()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(json(evidence.request())); + descriptor.setSourceEvidenceJson(json(fixture.source())); + return descriptor; + } + + private String json(Object value) { + try { + return new ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("Test evidence serialization failed", exception); + } + } + + private DriverManagerDataSource isolatedDataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + /** Seeds the immutable source/binding shape written before V41 added automatic delivery. */ + private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( + DSLContext isolatedDsl, + TransactionTemplate isolatedTransaction, + Game sourceGame, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW", + evidenceDigest); + + isolatedTransaction.execute( + status -> { + isolatedDsl.execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + isolatedDsl.execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, registration_request_id, " + + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Map legacyLaunchDescriptorSnapshot( + DSLContext isolatedDsl, String privateTenantKey, String controlPlaneRequestId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, created_at " + + "FROM launch_descriptor WHERE tenant_id = ? AND control_plane_request_id = ?", + privateTenantKey, + controlPlaneRequestId); + if (record == null) { + throw new IllegalStateException("Retained V34 launch descriptor fixture is missing"); + } + return record.intoMap(); + } + + private Map retainedReleaseBundleSnapshot(DSLContext isolatedDsl, long bundleId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, " + + "required_manifest_asset_keys_json, participant_digests_json, " + + "command_definitions_json, script_only, script_patch_version, published_at " + + "FROM published_release_bundle WHERE id = ?", + bundleId); + if (record == null) { + throw new IllegalStateException("Retained V34 release bundle fixture is missing"); + } + return record.intoMap(); + } + + private String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); + assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); + assertThat(actual.getGameTemplateId()).isEqualTo(expected.getGameTemplateId()); + assertThat(actual.getControlPlaneRequestId()).isEqualTo(expected.getControlPlaneRequestId()); + assertThat(actual.getRequestHash()).isEqualTo(expected.getRequestHash()); + assertThat(actual.getVersionId()).isEqualTo(expected.getVersionId()); + assertThat(actual.getScriptPatchVersion()).isEqualTo(expected.getScriptPatchVersion()); + assertThat(actual.getRuntimeFlagsJson()).isEqualTo(expected.getRuntimeFlagsJson()); + assertThat(actual.getGenerationConfigRevision()) + .isEqualTo(expected.getGenerationConfigRevision()); + assertThat(actual.getVersionStateEpoch()).isEqualTo(expected.getVersionStateEpoch()); + assertThat(actual.getReleaseBundleId()).isEqualTo(expected.getReleaseBundleId()); + assertThat(actual.getPublishedReleaseBundleRef()) + .isEqualTo(expected.getPublishedReleaseBundleRef()); + assertThat(actual.getRemapSetId()).isEqualTo(expected.getRemapSetId()); + assertThat(actual.getCreatedAt()).isEqualTo(expected.getCreatedAt()); + assertThat(actual.getDescriptorSchemaVersion()).isNull(); + assertThat(actual.getTargetNamespace()).isNull(); + assertThat(actual.getCanonicalTenantId()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); + assertThat(actual.getRequestDigest()).isNull(); + assertThat(actual.getResultDigest()).isNull(); + assertThat(actual.getOriginalRequestJson()).isNull(); + assertThat(actual.getSourceEvidenceJson()).isNull(); + } + + private record Fixture( + String controlPlaneRequestId, + UUID canonicalTenantId, + String privateSourceTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle) { + AuthoredWorldLaunchDescriptorEvidence.Request request() { + return request(controlPlaneRequestId); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + AuthoredWorldLaunchDescriptorEvidence.Request request(String requestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + true, + patch, + false, + null, + false, + null, + false, + null); + } } } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java index 98eee02d1d..241da0321c 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java @@ -1,240 +1,786 @@ package net.firedevops.firemud.gamedesign.service; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; 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.io.InputStream; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; -import java.util.Optional; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @ExtendWith(MockitoExtension.class) class AssetExportServiceImplTest { - @Mock private GameAssetRepository repository; - @Mock private VersionRepository versionRepository; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String PRIVATE_ENDPOINT = "http://minio.internal:9000"; + + @Mock private VersionAssetPublicationService publicationService; + @Mock private VersionAssetExportCandidateService candidateService; @Mock private S3Client s3Client; + private final AtomicReference storedCandidate = new AtomicReference<>(); + private final Map objectStore = new HashMap<>(); + private final Set failPutBeforeCommit = new HashSet<>(); + private final Set losePutAcknowledgementAfterCommit = new HashSet<>(); + private final Set failReadback = new HashSet<>(); + private AssetExportServiceImpl service; + private ExportSnapshot snapshot; @BeforeEach void setup() { - service = newService(256); + objectStore.clear(); + failPutBeforeCommit.clear(); + losePutAcknowledgementAfterCommit.clear(); + failReadback.clear(); + storedCandidate.set(null); + snapshot = singleAssetSnapshot(); + lenient() + .when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> snapshot); + lenient() + .when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> copySnapshot(snapshot)); + lenient() + .when( + candidateService.recordExportCandidate( + any(String.class), anyInt(), any(ExportedAssetManifest.class))) + .thenAnswer( + invocation -> { + ExportedAssetManifest requested = invocation.getArgument(2); + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + storedCandidate.set(requested); + existing = requested; + } + if (!existing.equals(requested)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + return existing; + }); + lenient() + .when(candidateService.readExportCandidate(any(String.class), anyInt())) + .thenAnswer( + ignored -> { + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + throw new IllegalStateException("candidate not found"); + } + return existing; + }); + lenient() + .when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer(this::putObject); + lenient() + .when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer(this::getObject); + service = newService(PUBLIC_BASE_URL); + } + + @Test + void readsAndMatchesDurableSnapshotBeforeConditionalObjectWrites() { + service.exportAssets(TENANT_ID, VERSION_NUMBER); + + InOrder order = inOrder(publicationService, candidateService, s3Client); + order.verify(publicationService).freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + order.verify(publicationService).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + order + .verify(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + order.verify(candidateService).readExportCandidate(TENANT_ID, VERSION_NUMBER); + order + .verify(s3Client) + .putObject( + argThat( + (PutObjectRequest request) -> + "*".equals(request.ifNoneMatch()) + && request.key().startsWith("artifacts/sha256/")), + any(RequestBody.class)); + } + + @Test + void unresolvedCandidateWriteBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("temporary candidate store failure")) + .when(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(candidateService, never()).readExportCandidate(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } - private AssetExportServiceImpl newService(int frozenSnapshotCacheMaxEntries) { - AssetStoreProperties props = new AssetStoreProperties(); - props.setBucket("bucket"); - props.setEndpoint("http://localhost:9000"); - props.setRegion("ap-southeast-2"); - props.setAccessKey("a"); - props.setSecretKey("s"); - props.setFrozenSnapshotCacheMaxEntries(frozenSnapshotCacheMaxEntries); - return new AssetExportServiceImpl( - repository, s3Client, props, new ObjectMapper(), versionRepository); + @Test + void unresolvedCandidateReadbackBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("candidate readback unavailable")) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } @Test - void exportUploadsAssetsAndManifest() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - GameAsset asset = gameAsset("logo.png", "data"); - when(repository.findByTenantId("t")).thenReturn(List.of(asset)); + void conflictingPersistedCandidateIsDeniedBeforeAnyObjectWrite() { + ExportedAssetManifest conflict = conflictingCandidate(); + org.mockito.Mockito.doReturn(conflict) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); - ExportedAssetManifest manifest = service.exportAssets("t", 1); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("ASSET_EXPORT_CANDIDATE_CONFLICT", thrown.getMessage()); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); + } + + @Test + void missingDurableSnapshotFailsClosedWithoutReadingCurrentAssetsOrWritingObjects() { + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(null); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_UNAVAILABLE", thrown.getMessage()); + verify(publicationService, never()).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + } + + @Test + void exportsCanonicalActualByteDigestsAndManifestWithoutPrivateStorageLocation() + throws Exception { + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(exported, storedCandidate.get()); + byte[] assetBytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String assetHex = sha256Hex(assetBytes); + String assetKey = "artifacts/sha256/" + assetHex; + assertEquals("sha256:" + assetHex, exported.artifactDigests().get(0).contentDigest()); + assertEquals(assetKey, exported.artifactDigests().get(0).immutableObjectKey()); + assertEquals(List.of("branding/logo"), exported.requiredManifestAssetKeys()); + assertEquals(1, exported.manifestSchemaVersion()); + assertEquals( + Set.of( + assetKey, "manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + assertEquals("sha256:" + sha256Hex(manifestBytes(exported)), exported.manifestHash()); + + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{\"branding/logo\":{\"usageKey\":\"branding/logo\"," + + "\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + assetKey + + "\",\"contentDigest\":\"sha256:" + + assetHex + + "\",\"contentType\":\"image/png\",\"artifactSchemaVersion\":1," + + "\"producerService\":\"game-design-service\",\"versionId\":\"" + + CANONICAL_VERSION_ID + + "\",\"url\":\"" + + PUBLIC_BASE_URL + + "/" + + assetKey + + "\"}}}", + manifestJson); + JsonNode manifest = new ObjectMapper().readTree(manifestJson); + assertEquals(1, manifest.get("schemaVersion").asInt()); + assertEquals(1, manifest.get("assets").size()); + assertEquals("branding/logo", manifest.get("assets").propertyNames().iterator().next()); + assertEquals(-1, manifestJson.indexOf("minio.internal")); + assertEquals(-1, manifestJson.indexOf("bucket")); verify(s3Client) .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/logo.png")), - any(RequestBody.class)); - verify(s3Client) - .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/manifest.json")), + argThat( + (PutObjectRequest request) -> + request + .key() + .equals( + "manifests/sha256/" + + exported.manifestHash().substring("sha256:".length())) + && "application/json".equals(request.contentType()) + && "*".equals(request.ifNoneMatch())), any(RequestBody.class)); - assertEquals(List.of("logo.png", "manifest.json"), manifest.requiredManifestAssetKeys()); } @Test - void sameVersionRetryReusesFrozenSnapshot() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + void emptyMappedSnapshotCreatesRealCanonicalEmptyManifest() throws Exception { + snapshot = snapshot(List.of()); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(List.of(), exported.requiredManifestAssetKeys()); + assertEquals(List.of(), exported.artifactDigests()); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{}}", + new String(manifestBytes(exported), StandardCharsets.UTF_8)); + assertEquals( + Set.of("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + } + + @Test + void serializesAssetsInExactUtf8ByteUsageOrder() { + String bmpKey = "\ue000"; + String supplementaryKey = "\ud800\udc00"; + snapshot = + snapshot( + List.of( + selection(supplementaryKey, 25L, "supplementary", "image/png"), + selection(bmpKey, 24L, "bmp", "image/png"))); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + + assertEquals(List.of(bmpKey, supplementaryKey), exported.requiredManifestAssetKeys()); + org.junit.jupiter.api.Assertions.assertTrue( + manifestJson.indexOf('"' + bmpKey + '"') + < manifestJson.indexOf('"' + supplementaryKey + '"')); + } - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + @Test + void serviceRestartReusesExactPersistedSnapshotAndImmutableKeys() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + AssetExportServiceImpl restarted = newService(PUBLIC_BASE_URL); + + ExportedAssetManifest retry = restarted.exportAssets(TENANT_ID, VERSION_NUMBER); assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + verify(publicationService, org.mockito.Mockito.times(2)) + .freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + verify(publicationService, org.mockito.Mockito.times(2)) + .readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + assertEquals(2, objectStore.size()); + } + + @Test + void rejectsIndependentlyReadSnapshotMismatchBeforeAnyStoreWrite() { + ExportSnapshot changedBytes = + snapshot(List.of(selection("branding/logo", 24L, "different uploaded bytes", "image/png"))); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(changedBytes); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", thrown.getMessage()); + assertEquals(0, objectStore.size()); + verifyNoInteractions(s3Client); } @Test - void unknownVersionIsRejectedWithoutSelectingTenantAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 99)).thenReturn(Optional.empty()); + void rejectsSnapshotSourceIdentityOrContentTypeSubstitutionBeforeAnyStoreWrite() { + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot(List.of(selection("branding/logo", 25L, "real uploaded bytes", "image/png")))); + + IllegalStateException changedSourceId = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedSourceId.getMessage()); + verifyNoInteractions(s3Client); - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> service.exportAssets("t", 99)); + org.mockito.Mockito.clearInvocations(publicationService); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot( + List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/jpeg")))); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(repository, s3Client); + IllegalStateException changedContentType = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedContentType.getMessage()); + verifyNoInteractions(s3Client); } @Test - void duplicateUsageKeysAreRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("logo.png", "one"), gameAsset("logo.png", "two"))); + void rejectsOutOfScopeOrIncompleteCanonicalSnapshotBeforeAnyStoreWrite() { + snapshot = + snapshot( + "another-tenant", + VERSION_NUMBER, + 19L, + 1L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + snapshot.items()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void reservedManifestUsageKeyIsRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("manifest.json", "asset data"))); + void rejectsNilCanonicalUuidBeforeAnyStoreWrite() { + snapshot = snapshot(List.of(), NIL_UUID, CANONICAL_VERSION_ID); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } - @ParameterizedTest - @EnumSource( - value = VersionLifecycleState.class, - names = {"PUBLISHED", "ACTIVE"}) - void publishedAndActiveRetryFailsWithoutFrozenSnapshot(VersionLifecycleState state) { - Version version = version(state); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)).thenReturn(Optional.of(version)); + @Test + void rejectsNonpositiveOwnerVersionIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot( + TENANT_ID, + VERSION_NUMBER, + 0L, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verify(repository, never()).findByTenantId("t"); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void publishedRetryReusesSnapshotFrozenBeforePublication() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); + void rejectsMalformedUtf8UsageKeyBeforeSortingOrWriting() { + snapshot = snapshot(List.of(selection("\ud800", 24L, "real uploaded bytes", "image/png"))); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: usageKey is not valid UTF-8", thrown.getMessage()); + verifyNoInteractions(s3Client); + } - assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + @Test + void rejectsDuplicateUsageKeysBeforeAnyStoreWrite() { + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/logo", 25L, "second", "image/png"))); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + verifyNoInteractions(s3Client); } @Test - void fullSnapshotCacheFailsClosedInsteadOfEvictingRetryEvidence() { - service = newService(1); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(7L, 1, VersionLifecycleState.DRAFT))); - when(versionRepository.findByTenantIdAndVersionNumber("t", 2)) - .thenReturn(Optional.of(version(8L, 2, VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn( - List.of(gameAsset("first.png", "first")), List.of(gameAsset("second.png", "second"))); + void rejectsReservedManifestKeyAndDuplicateSourceIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("manifest.json", 24L, "real uploaded bytes", "image/png"))); + + IllegalStateException reservedKey = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", reservedKey.getMessage()); + verifyNoInteractions(s3Client); + + org.mockito.Mockito.clearInvocations(publicationService); + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/icon", 24L, "second", "image/png"))); - service.exportAssets("t", 1); - org.mockito.Mockito.clearInvocations(s3Client); + IllegalStateException duplicateSource = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: duplicate source asset identity", + duplicateSource.getMessage()); + verifyNoInteractions(s3Client); + } + + @Test + void rejectsInvalidSourceIdentityAndDigestBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("branding/logo", 0L, "real uploaded bytes", "image/png"))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 2)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("EXPORT_SNAPSHOT_CAPACITY", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete source asset identity", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void publicationRacingSnapshotCreationFailsBeforeObjectStoreWrites() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(published)); - when(repository.findByTenantId("t")).thenReturn(List.of(gameAsset("logo.png", "data"))); + void rejectsSourceByteDigestMismatchBeforeAnyStoreWrite() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + snapshot = + snapshot( + List.of( + new AssetSelection( + "branding/logo", 24L, bytes, "image/png", "sha256:" + "f".repeat(64)))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); + assertEquals("ASSET_SOURCE_BYTES_MISMATCH", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void deleteExportedAssetsUsesExactManifestKeyList() { - service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json")); + void rejectsInvalidPublicOriginsBeforeAnyExternalWrites() { + for (String invalidBaseUrl : + Arrays.asList( + null, + "http://assets.example.invalid/assets", + "https://user@assets.example.invalid/assets", + "https://assets.example.invalid/assets?x=1", + "https://assets.example.invalid/assets#fragment", + "https://assets.example.invalid/private", + "https://minio.internal:9000/assets")) { + AssetExportServiceImpl invalidService = newService(invalidBaseUrl); + + assertThrows( + IllegalStateException.class, + () -> invalidService.exportAssets(TENANT_ID, VERSION_NUMBER), + String.valueOf(invalidBaseUrl)); + } + verifyNoInteractions(s3Client); + } - verify(s3Client) - .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/logo.png"))); - verify(s3Client) - .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/manifest.json"))); + @Test + void identicalConditionalExistingObjectsMakeRetryIdempotent() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + ExportedAssetManifest retry = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(first, retry); + assertEquals(2, objectStore.size()); + verify(s3Client, org.mockito.Mockito.times(4)) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedPreexistingObjectIsDeniedWithoutOverwritingOrDeletingIt() { + byte[] original = "original immutable bytes".getBytes(StandardCharsets.UTF_8); + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + objectStore.put(key, new StoredObject(original, "image/png")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertArrayEquals(original, objectStore.get(key).bytes()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(1, objectStore.size()); + } + + @Test + void lostPutAcknowledgementRecoversOnlyAfterExactCommittedReadback() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + losePutAcknowledgementAfterCommit.add(key); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals( + "sha256:" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)), + exported.artifactDigests().get(0).contentDigest()); + assertEquals(2, objectStore.size()); + } + + @Test + void unavailableReadbackAfterAmbiguousPutProducesOutcomePendingAndRetainsBytes() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failPutBeforeCommit.add(key); + failReadback.add(key); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(0, objectStore.size()); + } + + @Test + void unavailableReadbackAfterCommittedPutIsOutcomePendingWithoutCleanup() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failReadback.add(key); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void contentTypeMismatchOnReadbackDeniesObjectProof() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String key = "artifacts/sha256/" + sha256Hex(bytes); + objectStore.put(key, new StoredObject(bytes, "application/octet-stream")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void deleteFailsClosedWithoutIssuingAnyObjectDeletion() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.deleteExportedAssets(TENANT_ID, VERSION_NUMBER, List.of("branding/logo"))); + + assertEquals( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects", + thrown.getMessage()); + verifyNoInteractions(s3Client); + } + + private AssetExportServiceImpl newService(String publicBaseUrl) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint(PRIVATE_ENDPOINT); + properties.setPublicBaseUrl(publicBaseUrl); + return new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + private ExportedAssetManifest conflictingCandidate() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String hex = sha256Hex(bytes); + return new ExportedAssetManifest( + "sha256:" + "0".repeat(64), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + hex, + "sha256:" + hex, + "image/png", + 1))); + } + + private ExportSnapshot singleAssetSnapshot() { + return snapshot(List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/png"))); } - private static Version version(VersionLifecycleState state) { - return version(7L, 1, state); + private ExportSnapshot snapshot(List items) { + return snapshot(items, CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); } - private static Version version(Long id, int versionNumber, VersionLifecycleState state) { - Version version = new Version(); - version.setId(id); - version.setTenantId("t"); - version.setVersionNumber(versionNumber); - version.setVersionState(state); - return version; + private ExportSnapshot snapshot( + List items, UUID canonicalTenantId, UUID canonicalVersionId) { + return snapshot( + TENANT_ID, VERSION_NUMBER, 19L, 3L, canonicalTenantId, canonicalVersionId, items); } - private static GameAsset gameAsset(String fileName, String data) { - GameAsset asset = new GameAsset(); - asset.setTenantId("t"); - asset.setFileName(fileName); - asset.setContentType("image/png"); - asset.setData(data.getBytes(StandardCharsets.UTF_8)); - return asset; + private ExportSnapshot snapshot( + String tenantId, + int versionNumber, + long versionId, + long versionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + return new ExportSnapshot( + tenantId, + versionId, + versionNumber, + versionStateEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private static AssetSelection selection( + String usageKey, long assetId, String content, String contentType) { + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); + return new AssetSelection(usageKey, assetId, bytes, contentType, "sha256:" + sha256Hex(bytes)); + } + + private byte[] manifestBytes(ExportedAssetManifest exported) { + return objectStore + .get("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())) + .bytes(); + } + + private static ExportSnapshot copySnapshot(ExportSnapshot source) { + return new ExportSnapshot( + source.tenantId(), + source.versionId(), + source.versionNumber(), + source.capturedVersionStateEpoch(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.items().stream() + .map( + item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.bytes(), + item.contentType(), + item.contentDigest())) + .toList()); + } + + private software.amazon.awssdk.services.s3.model.PutObjectResponse putObject( + org.mockito.invocation.InvocationOnMock invocation) throws IOException { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + if (failPutBeforeCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put result before durable readback"); + } + if (objectStore.containsKey(request.key())) { + throw S3Exception.builder() + .statusCode(412) + .message("conditional object already exists") + .build(); + } + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + if (losePutAcknowledgementAfterCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put acknowledgement after commit"); + } + return PutObjectResponse.builder().build(); + } + + private ResponseBytes getObject( + org.mockito.invocation.InvocationOnMock invocation) { + GetObjectRequest request = invocation.getArgument(0); + if (failReadback.contains(request.key())) { + throw new IllegalStateException("simulated unavailable object readback"); + } + StoredObject object = objectStore.get(request.key()); + if (object == null) { + throw new IllegalStateException("simulated missing object readback"); + } + GetObjectResponse metadata = + GetObjectResponse.builder() + .contentType(object.contentType()) + .contentLength((long) object.bytes().length) + .build(); + return ResponseBytes.fromByteArray(metadata, object.bytes()); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) { + result.append(Character.forDigit((value >>> 4) & 0xf, 16)); + result.append(Character.forDigit(value & 0xf, 16)); + } + return result.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 6cdbaa103c..ce7ac958c7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -3,12 +3,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; @@ -29,6 +33,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { @AfterEach @@ -74,7 +79,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void launchReadsRequireExactSameNamespaceWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -93,12 +98,53 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { false, null, java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "1", 9L, "cp-1", null, null, null, null)) + AuthoredWorldLaunchDescriptorEvidence.Request launchRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "cp-1", + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + "silver-march", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + launchRequest, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:12345678-1234-4234-8234-123456789abc:7:11", + false, + null); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenReturn( new ResolvedLaunchDescriptorDto( - "ld-1", "1", 9L, "cp-1", 7L, null, "{}", "genrev-1", 11L, 11L, "prb:1:7:11", null)); + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence)); GameDesignGrpcService service = new GameDesignGrpcService( @@ -114,42 +160,53 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { new SimpleMeterRegistry()); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); AtomicReference bundleRef = new AtomicReference<>(); - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetPublishedReleaseBundleResponse value) { - bundleRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + underGameSessionPeer( + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetPublishedReleaseBundleResponse value) { + bundleRef.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); AtomicReference descriptorRef = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + underGameSessionPeer( + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-1") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(), + new StreamObserver<>() { + @Override + public void onNext(ResolveLaunchDescriptorResponse value) { + descriptorRef.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); @@ -158,4 +215,11 @@ public void onCompleted() {} assertEquals("", descriptorRef.get().getError().getCode()); assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); } + + private void underGameSessionPeer(Runnable operation) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 436a406852..47ce68a043 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -2,12 +2,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -29,6 +34,7 @@ import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; @@ -41,6 +47,8 @@ import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -82,8 +90,12 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); private final VersionService versionService = Mockito.mock(VersionService.class); @@ -183,23 +195,46 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "logo.png", + "branding-image", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "image/png", + 1)))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); - } + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); assertEquals("", ref.get().getError().getCode()); assertEquals(11L, ref.get().getBundle().getId()); assertEquals("abc123", ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals( + "opaque-release-reference-from-owner", + ref.get().getBundle().getPublishedReleaseBundleRef()); + assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); + assertEquals( + "82345678-1234-4234-8234-123456789abc", + ref.get().getBundle().getCanonicalVersionId()); + assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); + assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); + assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); @@ -1009,12 +1044,15 @@ void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("NOT_FOUND", ref.get().getError().getCode()); @@ -1041,135 +1079,188 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("SCHEMA_VERSION_UNSUPPORTED", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) + void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", + new PublishedReleaseBundleDto( + 11L, "tenant-1", - 9L, - "cp-1", 7L, - "patch-1", - "{}", + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + null, + "opaque-release-reference-from-owner", + null, + null)); - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + } - @Override - public void onCompleted() {} - }); - } + @Test + void resolveLaunchDescriptorReturnsDeterministicDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-1"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenReturn(launchDto(evidence)); + + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-1"), observerFor(ref))); assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService).resolveLaunchDescriptor(request); } @Test void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-2"), observerFor(ref))); assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); } @Test void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-3"), observerFor(ref))); - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + } - @Override - public void onCompleted() {} - }); - } + @Test + void getLaunchDescriptorReturnsExactBoundReadback() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-read"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when( + launchDescriptorService.getLaunchDescriptor( + Mockito.eq(UUID.fromString("32345678-1234-4234-8234-123456789abc")), + Mockito.eq(CANONICAL_TENANT_ID), + Mockito.eq("silver-march"), + Mockito.eq("cp-read"), + Mockito.eq(evidence.requestDigest()), + Mockito.eq(evidence.resultDigest()))) + .thenReturn(launchDto(evidence)); + + AtomicReference ref = new AtomicReference<>(); + var readRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest(evidence.requestDigest()) + .setExpectedResultDigest(evidence.resultDigest()) + .build(); + underLaunchPeer( + "world-management-service", () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); + + assertEquals("32345678-1234-4234-8234-123456789abc", ref.get().getRequestId()); + assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService) + .getLaunchDescriptor( + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest()); + } - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + @Test + void resolveLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + AtomicReference ref = new AtomicReference<>(); + var request = + resolveRequest("cp-unknown").toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void getLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + AtomicReference ref = new AtomicReference<>(); + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + underLaunchPeer( + "game-session-service", () -> service.getLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1476,6 +1567,78 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + controlPlaneRequestId, + CANONICAL_TENANT_ID, + "silver-march", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence launchEvidence( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + request.canonicalTenantId() + ":7:11", + false, + null); + } + + private ResolvedLaunchDescriptorDto launchDto(AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setGameTemplateId(9L) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 78f7b1d6ec..378f8aa1c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -1,13 +1,28 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -15,6 +30,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -24,21 +40,111 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.test.util.ReflectionTestUtils; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { + private static final String NAMESPACE = "test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @Mock private VersionRepository versionRepository; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private TemplateRemapSetService templateRemapSetService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private LaunchDescriptorServiceImpl service; + @Test + void completeSelectorV2ResolvesTheUnchangedDescriptorV1Binding() throws Exception { + var request = request("cp-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + var bundle = selectorBundle(false); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(bundle); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(7L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertEquals( + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION, + resolved.authoredWorldBinding().schemaVersion()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(17L, resolved.versionStateEpoch()); + verify(launchDescriptorRepository).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSuccess() + throws Exception { + var request = request("cp-incomplete-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(selectorBundle(true)); + + assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { + // Stipulated original component bytes; this fixture does not authenticate a producer or admit + // gameplay. + WorldPublishedStartLocationEvidence evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 7L, + PRIVATE_SOURCE_TENANT_KEY, + 1L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + return new PublishedReleaseBundleDto( + 11L, + PRIVATE_SOURCE_TENANT_KEY, + 7L, + 8, + "v2", + evidence.request().publishWorkflowId(), + MANIFEST_HASH, + List.of(), + omitParticipant ? participants.subList(0, 4) : participants, + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + 1, + List.of(), + evidence); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); service = new LaunchDescriptorServiceImpl( gameTemplateRepository, @@ -46,122 +152,387 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); } @Test - void resolveLaunchDescriptorPersistsDeterministicDescriptor() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); + void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-1", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + AtomicReference inserted = new AtomicReference<>(); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(7L, resolved.versionId()); + assertEquals("genrev-1", resolved.generationConfigRevision()); + assertEquals(17L, resolved.versionStateEpoch()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals( + PRIVATE_SOURCE_TENANT_KEY, + inserted.get().getTenantId(), + "The private source key remains owner-local and is not the canonical tenant UUID"); + assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); + verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); + } + + @Test + void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOrRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(7L, 11L, "v1"); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-retry")) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + var first = service.resolveLaunchDescriptor(request); + when(template.getDefaultVersionId()).thenReturn(8L); when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) + clearInvocations(template); + when(versionRepository.findById(8L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 8L)); + + var retry = service.resolveLaunchDescriptor(request); + + assertEquals(first, retry); + assertEquals(7L, retry.versionId()); + verify(gameTemplateRepository, times(1)) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verifyNoInteractions(template); + verify(versionRepository, times(1)).findById(7L); + verify(versionRepository, never()).findById(8L); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L); + verify(launchDescriptorRepository, times(1)).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void changedSourceScopeTemplateOrRequestCannotReplaceOriginalDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request original = request("cp-conflict", 9L); + stubSuccessfulLaunch(original, 7L, 11L); + LaunchDescriptor stored = descriptorFor(original, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-conflict")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + AuthoredWorldLaunchDescriptorEvidence.Request changedTemplate = request("cp-conflict", 10L); + IllegalArgumentException templateConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedTemplate)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + templateConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedRequest = + request("cp-conflict", 9L, true, "other-patch"); + IllegalArgumentException requestConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedRequest)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + requestConflict.getMessage()); + + UUID otherOperation = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedSource = + request("cp-conflict", 9L, otherOperation, WORLD_SLUG, CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + otherOperation, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + IllegalArgumentException sourceConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedSource)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + sourceConflict.getMessage()); + + UUID otherCanonicalTenant = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedTenantScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, WORLD_SLUG, otherCanonicalTenant); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, otherCanonicalTenant, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException scopeConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedTenantScope)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + scopeConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedWorldScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, "other-world", CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, "other-world", NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException worldConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedWorldScope)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + worldConflict.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactReadbackReturnsOriginalEvidenceAndRejectsDigestOrScopeSubstitution() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-read", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-read")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); + var original = service.resolveLaunchDescriptor(request); + + var readback = + service.getLaunchDescriptor( + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + + assertEquals(original, readback); + IllegalArgumentException changedRequestDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("72345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + "sha256:" + "b".repeat(64), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedRequestDigest.getMessage()); - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); + IllegalArgumentException changedResultDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + "sha256:" + "c".repeat(64))); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedResultDigest.getMessage()); - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); + IllegalArgumentException changedWorld = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + "other-world", + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedWorld.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } @Test - void resolveLaunchDescriptorRejectsConflictingRequestReuse() { - LaunchDescriptor existing = new LaunchDescriptor(); - existing.setRequestHash("other-hash"); - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.of(existing)); + void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-patch", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, "patch-1"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", + thrown.getMessage()); + verify(template).getDefaultScriptPatchVersion(); + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); + assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); + assertEquals(null, failure.getValue().getLaunchDescriptorId()); + assertEquals(null, failure.getValue().getVersionId()); + } + + @Test + void sourceAndTransientDependencyFailuresDoNotCreateFrozenOutcomes() { + AuthoredWorldLaunchDescriptorEvidence.Request missingSource = request("cp-no-source", 9L); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + + IllegalArgumentException sourceFailure = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(missingSource)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + sourceFailure.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedSourceEvidence = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "cp-changed-source", + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + "sha256:" + "f".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + stubSource(changedSourceEvidence, sourceEvidence(WORLD_SLUG)); assertThrows( IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + () -> service.resolveLaunchDescriptor(changedSourceEvidence)); + + AuthoredWorldLaunchDescriptorEvidence.Request unavailableDependency = + request("cp-unavailable", 9L); + stubSource(unavailableDependency, sourceEvidence(WORLD_SLUG)); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L)) + .thenThrow(new DataAccessResourceFailureException("temporary database outage")); + + assertThrows( + DataAccessResourceFailureException.class, + () -> service.resolveLaunchDescriptor(unavailableDependency)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-frozen-failure", 9L); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + LaunchDescriptor failure = new LaunchDescriptor(); + failure.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + failure.setControlPlaneRequestId(request.controlPlaneRequestId()); + failure.setRequestHash(request.requestDigest()); + failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + failure.setTargetNamespace(NAMESPACE); + failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + failure.setRequestDigest(request.requestDigest()); + failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + failure.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + failure.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + failure.setFailureCode("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + failure.setFailureMessage("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(failure)); + stubSource(request, source); + + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", thrown.failureCode()); + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial", thrown.getMessage()); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setScriptPatchVersion("patch-1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-tampered")) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorPreservesTemplatePhaseGate() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.LEGACY); + stubSource(request, sourceEvidence(WORLD_SLUG)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced", + thrown.getMessage()); } @Test void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v2", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-schema", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v999")); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( true, @@ -173,33 +544,16 @@ void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { @Test void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-2")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException("tenant-1", 7L)); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-release", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 7L)); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-2", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", @@ -207,34 +561,107 @@ void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { } @Test - void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-3")) + void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-reference", 9L); + stubTemplate(request, 7L, null); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v1", null)); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + IllegalArgumentException first = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + IllegalArgumentException retry = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: published release bundle has no persisted opaque reference", + first.getMessage()); + assertEquals(first.getMessage(), retry.getMessage()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, stored.get().getOutcomeStatus()); + assertEquals("RELEASE_BUNDLE_NOT_FOUND", stored.get().getFailureCode()); + assertNull(stored.get().getPublishedReleaseBundleRef()); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); + Long resolvedVersionId = boxedLargeVersionId(); + Long bundleVersionId = boxedLargeVersionId(); + assertNotSame(resolvedVersionId, bundleVersionId); + stubTemplate(request, resolvedVersionId, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(bundleVersionId, 11L, "v1")); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(1_000L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + } + + @Test + void resolveLaunchDescriptorRejectsReleaseBundleForDifferentVersionDeterministically() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-mismatched-release", 9L); + stubTemplate(request, 1_000L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(1_001L, 11L, "v1")); + IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: release bundle is not owned by the resolved source version", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-required", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", @@ -243,61 +670,292 @@ void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { @Test void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(8L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-4")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-approved", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) .thenReturn( Optional.of( new TemplateRemapSetDto( "remap-1", - "tenant-1", + PRIVATE_SOURCE_TENANT_KEY, 7L, 8L, TemplateRemapSetStatus.APPROVED, - "prep", + "preparation", "approved", LocalDateTime.now(), LocalDateTime.now(), List.of()))); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 8L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 8L, - 9, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + stubBundle(8L, 11L, "v1"); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - var descriptor = service.resolveLaunchDescriptor("tenant-1", 9L, "cp-4", null, 7L, 8L, null); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals("remap-1", resolved.remapSetId()); + assertEquals("remap-1", resolved.authoredWorldBinding().remapSetId()); + } + + private void stubSuccessfulLaunch( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + stubTemplate(request, versionId, null); + stubSource(request, sourceEvidence(request.worldSlug())); + stubVersion(versionId, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(versionId, bundleId, "v1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + } + + private GameTemplateLaunchConfigView stubTemplate( + AuthoredWorldLaunchDescriptorEvidence.Request request, + Long defaultVersionId, + String defaultPatch) { + GameTemplateLaunchConfigView template = Mockito.mock(GameTemplateLaunchConfigView.class); + when(template.getId()).thenReturn(request.gameTemplateId()); + when(template.getTenantId()).thenReturn(PRIVATE_SOURCE_TENANT_KEY); + when(template.getDefaultVersionId()).thenReturn(defaultVersionId); + when(template.getDefaultScriptPatchVersion()).thenReturn(defaultPatch); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId( + PRIVATE_SOURCE_TENANT_KEY, request.gameTemplateId())) + .thenReturn(Optional.of(template)); + return template; + } + + private void stubSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + when(authoredWorldSourceRepository.read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(source)); + } + + private void stubVersion( + long versionId, VersionLifecycleState state, long epoch, String scriptPatchVersion) { + Version version = new Version(); + version.setId(versionId); + version.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + version.setVersionNumber(8); + version.setVersionState(state); + version.setVersionStateEpoch(epoch); + version.setScriptPatchVersion(scriptPatchVersion); + version.setUpdatedAt(LocalDateTime.now()); + when(versionRepository.findById(versionId)).thenReturn(Optional.of(version)); + } + + private void stubBundle(long versionId, long bundleId, String schemaVersion) { + when(publishedReleaseBundleService.getPublishedReleaseBundle( + PRIVATE_SOURCE_TENANT_KEY, versionId)) + .thenReturn(releaseBundle(versionId, bundleId, schemaVersion)); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion) { + return releaseBundle(versionId, bundleId, schemaVersion, PUBLISHED_RELEASE_BUNDLE_REF); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion, String publishedReleaseBundleRef) { + return new PublishedReleaseBundleDto( + bundleId, + PRIVATE_SOURCE_TENANT_KEY, + versionId, + 8, + schemaVersion, + "workflow-1", + MANIFEST_HASH, + List.of(), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + publishedReleaseBundleRef, + 1, + List.of()); + } + + @SuppressWarnings("removal") + private Long boxedLargeVersionId() { + return new Long(1_000L); + } + + private LaunchDescriptor descriptorFor( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-stored-" + request.controlPlaneRequestId(), + versionId, + false, + null, + "{}", + "genrev-1", + 17L, + bundleId, + PUBLISHED_RELEASE_BUNDLE_REF, + false, + null); + AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + descriptor.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + return descriptor; + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String tenantSlug = "silver-company"; + String displayName = "Silver March 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, long gameTemplateId) { + return request( + controlPlaneRequestId, + gameTemplateId, + SOURCE_OPERATION_ID, + WORLD_SLUG, + CANONICAL_TENANT_ID); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + long sourceVersionId, + long targetVersionId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + true, + sourceVersionId, + true, + targetVersionId, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + requestedPatchPresent, + requestedPatch, + false, + null, + false, + null, + false, + null); + } - assertEquals("remap-1", descriptor.remapSetId()); + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + UUID operationId, + String worldSlug, + UUID canonicalTenantId) { + String evidenceDigest = + SOURCE_OPERATION_ID.equals(operationId) + && WORLD_SLUG.equals(worldSlug) + && CANONICAL_TENANT_ID.equals(canonicalTenantId) + ? sourceEvidence(WORLD_SLUG).evidenceDigest() + : "sha256:" + "a".repeat(64); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + operationId, + evidenceDigest, + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 22cfa90253..fabdc0d60f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -2,22 +2,32 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Revision; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -25,16 +35,237 @@ import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + @Mock private PublishedReleaseBundleRepository repository; @Mock private RevisionRepository revisionRepository; + @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; + @Test + void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + // ISOLATED source-repository response; this test covers service assembly only. + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-release"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(saved)); + return saved; + }); + var first = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence); + assertEquals("v2", first.attestationSchemaVersion()); + assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + org.mockito.Mockito.clearInvocations(versionRepository, revisionRepository, repository); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.empty()); + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + WorldPublishedStartLocationEvidence.fromStored(evidence.canonicalBytes())); + assertEquals(first.id(), retry.id()); + assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(first.worldPublishedStartLocationEvidence().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(versionRepository, revisionRepository); + org.mockito.Mockito.verify(repository) + .requireSelectedCommandDefinitions(any(), any(), any(), any()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "changed", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + assertThatThrownBy( + () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + } + + @Test + void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "wrong-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants.subList(0, 4), + evidence)) + .isInstanceOf(IllegalArgumentException.class); + var world = participants.getFirst(); + var changed = new java.util.ArrayList<>(participants); + changed.set( + 0, + new PublishParticipantDigestDto( + world.participantKey(), + world.scopeValue(), + null, + world.appliedCommitId(), + "e".repeat(64), + 3, + null, + null, + null)); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + changed, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + var evidence = selectorEvidence(); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + } + + @Test + void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() + throws Exception { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v1"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + assertNull( + service.getPublishedReleaseBundle("tenant-1", 7L).worldPublishedStartLocationEvidence()); + var evidence = selectorEvidence(); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selector-ineligible"); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + retained.setAttestationSchemaVersion("v2"); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + } + + private VersionDto selectorVersion() { + return new VersionDto( + 7L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); service = - new PublishedReleaseBundleServiceImpl(repository, revisionRepository, new ObjectMapper()); + new PublishedReleaseBundleServiceImpl( + repository, revisionRepository, versionRepository, new ObjectMapper()); + Version source = new Version(); + source.setId(7L); + source.setTenantId("tenant-1"); + source.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + source.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(source)); } @Test @@ -63,6 +294,7 @@ void createFullVersionBundlePersistsImmutableAttestation() { invocation -> { PublishedReleaseBundle entity = invocation.getArgument(0); entity.setId(11L); + entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); return entity; }); @@ -70,21 +302,79 @@ void createFullVersionBundlePersistsImmutableAttestation() { service.createFullVersionBundle( version, "workflow-1", - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")), + logoManifest(), "genrev-1", List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-v1", + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null))); assertEquals(11L, dto.id()); assertEquals("tenant-1", dto.tenantId()); assertEquals(7L, dto.versionId()); - assertEquals("abc123", dto.manifestHash()); + assertEquals(MANIFEST_HASH, dto.manifestHash()); + assertEquals(1, dto.manifestSchemaVersion()); + assertEquals(List.of(logoProof()), dto.artifactDigests()); assertEquals("genrev-1", dto.generationConfigRevision()); - assertEquals(List.of("logo.png", "manifest.json"), dto.requiredManifestAssetKeys()); - assertEquals(1, dto.participantDigests().size()); + assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); + assertEquals(2, dto.participantDigests().size()); + assertEquals("GAME_LOGIC", dto.participantDigests().getFirst().participantKey()); + assertEquals("version:7", dto.participantDigests().getFirst().appliedCommitId()); + assertEquals("digest-logic", dto.participantDigests().getFirst().contentDigest()); + assertEquals(1, dto.participantDigests().getFirst().digestSchemaVersion()); + assertEquals("ability-schema-v1", dto.participantDigests().getFirst().abilitySchemaDigest()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); assertEquals("v1", dto.attestationSchemaVersion()); + assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); + assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); + assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); + org.mockito.Mockito.verify(repository) + .save( + org.mockito.ArgumentMatchers.argThat( + saved -> + sourceIdentity().getCanonicalTenantId().equals(saved.getCanonicalTenantId()) + && sourceIdentity() + .getCanonicalVersionId() + .equals(saved.getCanonicalVersionId()))); + } + + @Test + void retainedBundleWithoutCanonicalIdentityStaysAbsent() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setParticipantDigestsJson( + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"7\"," + + "\"baseVersionId\":null,\"appliedCommitId\":\"version:7\"," + + "\"contentDigest\":\"legacy-aggregate\",\"digestSchemaVersion\":1," + + "\"errorCode\":null,\"errorMessage\":null}]"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + + var dto = service.findPublishedReleaseBundle("tenant-1", 7L).orElseThrow(); + + assertNull(dto.canonicalTenantId()); + assertNull(dto.canonicalVersionId()); + assertNull(dto.publishedReleaseBundleRef()); + assertNull(dto.manifestSchemaVersion()); + assertNull(dto.artifactDigests()); + assertNull(dto.participantDigests().getFirst().abilitySchemaDigest()); + } + + private Version sourceIdentity() { + Version version = new Version(); + version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + return version; } @Test @@ -109,11 +399,7 @@ void createFullVersionBundleRejectsDuplicateAttestation() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -154,11 +440,7 @@ void createFullVersionBundleRejectsDuplicateCommandDefinitionAlias() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -176,11 +458,7 @@ void createFullVersionBundleRejectsDuplicateCanonicalCommandIds() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -198,11 +476,7 @@ void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -219,11 +493,7 @@ void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { IllegalArgumentException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } private VersionDto version() { @@ -240,4 +510,22 @@ private VersionDto version() { LocalDateTime.now(), LocalDateTime.now()); } + + private static ExportedAssetManifest emptyManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); + } + + private static ExportedAssetManifest logoManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof())); + } + + private static PublishedArtifactDigest logoProof() { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + LOGO_DIGEST.substring("sha256:".length()), + LOGO_DIGEST, + "image/png", + 1); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 66a2b9a944..0cfc1f29a5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; @@ -696,6 +697,36 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { verify(publishAttemptService, never()).executeFullVersionTransaction(any()); } + @Test + void uncertainAssetExportRemainsPendingForExactRetry() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)) + .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + @Test void readbackWithArtifactButNoBundleRemainsPartial() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index ca97ef1158..d2ab877f64 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -21,7 +21,6 @@ import net.firedevops.firemud.gamedesign.v1.HelpTopicScope; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicRequest; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.service.GameAuthoredHelpReader; import net.firedevops.firemud.shared.v1.ErrorDetail; @@ -64,7 +63,7 @@ protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( long tenantId, long gameTemplateId, String controlPlaneRequestId) { - return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); + return authoredWorldLaunchBindingRequired(); } public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( @@ -73,18 +72,7 @@ public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( String controlPlaneRequestId, Long sourceVersionId, Long targetVersionId) { - ResolveLaunchDescriptorRequest.Builder request = - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameTemplateId(gameTemplateId) - .setControlPlaneRequestId(controlPlaneRequestId); - if (sourceVersionId != null) { - request.setSourceVersionId(sourceVersionId); - } - if (targetVersionId != null) { - request.setTargetVersionId(targetVersionId); - } - return callStub().resolveLaunchDescriptor(request.build()); + return authoredWorldLaunchBindingRequired(); } public GetPublishedReleaseBundleResponse getPublishedReleaseBundle( @@ -193,6 +181,17 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub callStub() { return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); } + private static ResolveLaunchDescriptorResponse authoredWorldLaunchBindingRequired() { + return ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build(); + } + private static GetPublishedScriptPatchVersionResponse unavailableScriptPatchVersion() { return GetPublishedScriptPatchVersionResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index b090816e15..acf2340aa7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -1220,69 +1220,9 @@ private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { } private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { - if (gameDesignClient == null) { - throw new IllegalStateException("launch descriptor authority unavailable"); - } - var descriptorResponse = - gameDesignClient.resolveLaunchDescriptor( - request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); - if (descriptorResponse.hasError()) { - throw new IllegalArgumentException( - descriptorResponse.getError().getCode() - + ": " - + descriptorResponse.getError().getMessage()); - } - var descriptor = descriptorResponse.getLaunchDescriptor(); - var bundleResponse = - gameDesignClient.getPublishedReleaseBundle(request.tenantId(), descriptor.getVersionId()); - if (bundleResponse.hasError()) { - throw new IllegalArgumentException( - bundleResponse.getError().getCode() + ": " + bundleResponse.getError().getMessage()); - } - var bundle = bundleResponse.getBundle(); - requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); - if (bundle.getId() != descriptor.getReleaseBundleId() - || bundle.getVersionId() != descriptor.getVersionId() - || !bundle.getGenerationConfigRevision().equals(descriptor.getGenerationConfigRevision()) - || !releaseBundleRef(request.tenantId(), descriptor.getVersionId(), bundle.getId()) - .equals(descriptor.getPublishedReleaseBundleRef())) { - throw new IllegalArgumentException( - "RELEASE_ATTESTATION_MISMATCH: resolved launch descriptor does not match the published" - + " release bundle"); - } - validatePublishedAssetProof(request.tenantId(), descriptor.getVersionId(), bundle); - var versionStateResponse = - gameDesignClient.getVersionState(request.tenantId(), descriptor.getVersionId()); - if (versionStateResponse.hasError()) { - throw new IllegalArgumentException( - versionStateResponse.getError().getCode() - + ": " - + versionStateResponse.getError().getMessage()); - } - var versionState = versionStateResponse.getVersionState(); - if (versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED - && versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); - } - if (versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch()) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved launch descriptor epoch does not match current" - + " version state"); - } - return new ResolvedLaunchDescriptor( - descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" + + " required"); } private void validatePublishedAssetProof( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index 4bd79f5990..8c9a4d9d96 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -12,6 +12,8 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -34,13 +36,54 @@ void rejectsNonpositiveBaseVersionAsInvalidArgumentWithoutCallingGameDesign(long verifyNoInteractions(stub); } + @Test + void legacyNumericLaunchResolveFailsClosedWithoutStubOrChannelInteraction() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = client.resolveLaunchDescriptor(1L, 9L, "cp-1"); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void legacyNumericReplacementLaunchResolveFailsClosedWithoutStubOrChannelInteraction() + throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = + client.resolveLaunchDescriptor(1L, 9L, "cp-1", 7L, 8L); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + private static void assertLaunchBindingRequired(ResolveLaunchDescriptorResponse response) { + assertThat(response.getError().getCode()).isEqualTo("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); + assertThat(response.getError().getMessage()) + .contains("Canonical authored-world source binding is required"); + } + private static GameDesignClient newClient( GameDesignServiceGrpc.GameDesignServiceBlockingStub stub) throws Exception { + return newClient(stub, mock(GrpcChannelFactory.class)); + } + + private static GameDesignClient newClient( + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub, + GrpcChannelFactory channelFactory) + throws Exception { GameDesignClient client = new GameDesignClient( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), - mock(GrpcChannelFactory.class), + channelFactory, BlockingGrpcStubCustomizer.noop()); Field field = AbstractBlockingGrpcClient.class.getDeclaredField("stub"); field.setAccessible(true); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index f3f26bc9b6..9161200d9e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -130,6 +130,13 @@ void startSessionSavesState() { assertNull(store.get(10L).getScriptPinEpoch()); } + @Test + void legacyNumericLaunchFailsClosedBeforeMutation() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-numeric-launch", 42L); + + assertNumericLaunchDeniedWithoutMutation(request); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); @@ -1468,6 +1475,21 @@ private void configureLaunchPreflight() { .build()); } + private void assertNumericLaunchDeniedWithoutMutation(StartSessionRequest request) { + Map before = new HashMap<>(); + store.forEach((id, instance) -> before.put(id, copyOf(instance))); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" + + " required", + error.getMessage()); + org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); + verifyNoInteractions(repository, gameDesignClient, worldManagementClient, stateService); + } + @Test void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", 42L); From b434a43cfc6e64d43f316b0bf2368d2eca35d4b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:38:37 +1300 Subject: [PATCH 03/29] refactor: separate canonical launch consumer from source foundation --- .../game-design/v1/game_design_service.proto | 50 +- .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../service/LaunchDescriptorService.java | 24 +- ...FrozenLaunchDescriptorDenialException.java | 23 - .../service/impl/GameDesignGrpcService.java | 239 +--- .../impl/LaunchDescriptorServiceImpl.java | 669 +---------- ...aunchDescriptorServiceIntegrationTest.java | 1051 +---------------- .../impl/GameDesignGrpcServiceAuthTest.java | 84 +- .../impl/GameDesignGrpcServiceTest.java | 207 +--- .../impl/LaunchDescriptorServiceImplTest.java | 971 +-------------- .../service/impl/GameInstanceServiceImpl.java | 66 +- .../impl/GameInstanceServiceImplTest.java | 22 +- 12 files changed, 192 insertions(+), 3248 deletions(-) delete mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 081557fc54..5f849b4040 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,7 +35,6 @@ service GameDesignService { returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); - rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -338,16 +337,13 @@ message CompareAndSetVersionStateResponse { } message ResolveLaunchDescriptorRequest { - string canonical_tenant_id = 1; + string tenant_id = 1; int64 game_template_id = 2; string control_plane_request_id = 3; optional string requested_script_patch_version = 4; 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; } message ResolveLaunchDescriptorResponse { @@ -502,47 +498,6 @@ message PublishedReleaseBundle { repeated PublishedArtifactDigest artifact_digests = 21; } -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 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; -} - message PublishedArtifactDigest { string usage_key = 1; string artifact_kind = 2; @@ -554,7 +509,7 @@ message PublishedArtifactDigest { message LaunchDescriptor { string launch_descriptor_id = 1; - string canonical_tenant_id = 2; + string tenant_id = 2; int64 game_template_id = 3; string control_plane_request_id = 4; int64 version_id = 5; @@ -565,7 +520,6 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; - AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; } message TemplateRemapSet { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java index 363db4bd74..251dc5129e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java @@ -1,10 +1,8 @@ package net.firedevops.firemud.gamedesign.dto; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; - public record ResolvedLaunchDescriptorDto( String launchDescriptorId, - String canonicalTenantId, + String tenantId, long gameTemplateId, String controlPlaneRequestId, long versionId, @@ -14,5 +12,31 @@ public record ResolvedLaunchDescriptorDto( long versionStateEpoch, long releaseBundleId, String publishedReleaseBundleRef, - String remapSetId, - AuthoredWorldLaunchDescriptorEvidence authoredWorldBinding) {} + String remapSetId) { + public ResolvedLaunchDescriptorDto( + String launchDescriptorId, + String tenantId, + long gameTemplateId, + String controlPlaneRequestId, + long versionId, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef) { + this( + launchDescriptorId, + tenantId, + gameTemplateId, + controlPlaneRequestId, + versionId, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + null); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index cf337ee6e8..6403542e21 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -1,26 +1,14 @@ package net.firedevops.firemud.gamedesign.service; -import java.util.UUID; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; public interface LaunchDescriptorService { ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - AuthoredWorldLaunchDescriptorEvidence.Request request); - - ResolvedLaunchDescriptorDto getLaunchDescriptor( - UUID readRequestId, - UUID canonicalTenantId, - String worldSlug, - String controlPlaneRequestId, - String expectedRequestDigest, - String expectedResultDigest); - - ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( - UUID readRequestId, - UUID canonicalTenantId, - String worldSlug, + String tenantId, + long gameTemplateId, String controlPlaneRequestId, - String expectedRequestDigest, - String expectedResultDigest); + String requestedScriptPatchVersion, + Long sourceVersionId, + Long targetVersionId, + String requestedRuntimeFlagsJson); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java deleted file mode 100644 index 5bc425144a..0000000000 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.firedevops.firemud.gamedesign.service.impl; - -/** A deterministic launch business denial whose exact request outcome is stored by the owner. */ -final class FrozenLaunchDescriptorDenialException extends IllegalArgumentException { - private final String failureCode; - - static FrozenLaunchDescriptorDenialException create(String failureCode, String detail) { - return new FrozenLaunchDescriptorDenialException(failureCode, failureCode + ": " + detail); - } - - private FrozenLaunchDescriptorDenialException(String failureCode, String message) { - super(message); - this.failureCode = failureCode; - } - - static FrozenLaunchDescriptorDenialException fromStored(String failureCode, String message) { - return new FrozenLaunchDescriptorDenialException(failureCode, message); - } - - String failureCode() { - return failureCode; - } -} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index efc0fd705b..ed7471a71c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -10,7 +10,6 @@ import java.util.List; import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; @@ -55,8 +54,6 @@ import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsRequest; import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsResponse; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; @@ -892,122 +889,17 @@ public void compareAndSetVersionState( public void resolveLaunchDescriptor( ResolveLaunchDescriptorRequest request, StreamObserver responseObserver) { - ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); - try { - requireLaunchDescriptorResolveAccess(); - UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); - UUID sourceOperationId = - parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); - if (canonicalTenantId == null - || sourceOperationId == null - || !request.getUnknownFields().asMap().isEmpty()) { - throw new IllegalArgumentException("Closed canonical authored-world request is required"); - } - AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = - new AuthoredWorldLaunchDescriptorEvidence.Request( - workloadNamespace, - request.getControlPlaneRequestId(), - canonicalTenantId, - request.getWorldSlug(), - sourceOperationId, - request.getExpectedAuthoredWorldSourceEvidenceDigest(), - request.getGameTemplateId(), - request.hasRequestedScriptPatchVersion(), - request.hasRequestedScriptPatchVersion() - ? request.getRequestedScriptPatchVersion() - : null, - request.hasSourceVersionId(), - request.hasSourceVersionId() ? request.getSourceVersionId() : null, - request.hasTargetVersionId(), - request.hasTargetVersionId() ? request.getTargetVersionId() : null, - request.hasRequestedRuntimeFlagsJson(), - request.hasRequestedRuntimeFlagsJson() - ? request.getRequestedRuntimeFlagsJson() - : null); - var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); - builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); - } catch (AdminAuthorizationException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - "PERMISSION_DENIED", - ex.getMessage())); - } catch (IllegalStateException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), true), - ex.getMessage())); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), true), - ex.getMessage())); - } catch (IllegalStateException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), true), - ex.getMessage())); - } catch (Exception ex) { - builder.setError( - GrpcAppErrors.internal(meterRegistry, logger, "ResolveLaunchDescriptor", ex)); - } - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } - - @Override - @Timed(value = "gamedesignGrpc.getLaunchDescriptor") - public void getLaunchDescriptor( - GetLaunchDescriptorRequest request, - StreamObserver responseObserver) { - GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); - try { - requireLaunchDescriptorReadAccess(); - UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); - UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); - if (readRequestId == null - || canonicalTenantId == null - || !request.getUnknownFields().asMap().isEmpty()) { - throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); - } - var descriptor = - launchDescriptorService.getLaunchDescriptor( - readRequestId, - canonicalTenantId, - request.getWorldSlug(), - request.getControlPlaneRequestId(), - request.getExpectedRequestDigest(), - request.getExpectedResultDigest()); - builder - .setRequestId(readRequestId.toString()) - .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); - } catch (AdminAuthorizationException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "GetLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), true), - ex.getMessage())); - } catch (Exception ex) { - builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); - } - responseObserver.onNext(builder.build()); + ResolveLaunchDescriptorResponse response = + ResolveLaunchDescriptorResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", + "Canonical authored-world launch binding is required")) + .build(); + responseObserver.onNext(response); responseObserver.onCompleted(); } @@ -2038,80 +1930,6 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } - private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( - net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { - AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); - if (evidence == null) { - throw new IllegalStateException("Bound authored-world launch evidence is required"); - } - evidence.requireValid(); - var 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 net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setCanonicalTenantId(descriptor.canonicalTenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .setAuthoredWorldBinding(binding.build()) - .build(); - } - - private UUID parseCanonicalNonNilUuid(String value) { - if (value == null) { - return null; - } - try { - UUID parsed = UUID.fromString(value); - return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; - } catch (IllegalArgumentException exception) { - return null; - } - } - private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { UUID canonicalTenantId = bundle.canonicalTenantId(); UUID canonicalVersionId = bundle.canonicalVersionId(); @@ -2149,14 +1967,6 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } - if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") - || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { - return "NOT_FOUND"; - } - if (message.startsWith("AUTHORED_WORLD_SOURCE_") - || message.startsWith("LAUNCH_DESCRIPTOR_")) { - return "FAILED_PRECONDITION"; - } return "INVALID_ARGUMENT"; } @@ -2244,22 +2054,6 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } - private void requireLaunchDescriptorResolveAccess() { - requireExactWorkloadPeer("game-session-service"); - } - - private void requireLaunchDescriptorReadAccess() { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) - || peer == null - || !workloadNamespace.equals(peer.namespace()) - || !(peer.isService("game-session-service") - || peer.isService("world-management-service"))) { - throw new AdminAuthorizationException( - "Exact same-namespace Game Session or World Management workload identity is required"); - } - } - private void requirePublishedReleaseBundleReadAccess() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) @@ -2273,17 +2067,6 @@ private void requirePublishedReleaseBundleReadAccess() { } } - private void requireExactWorkloadPeer(String service) { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) - || peer == null - || !workloadNamespace.equals(peer.namespace()) - || !peer.isService(service)) { - throw new AdminAuthorizationException( - "Exact same-namespace workload identity is required for launch descriptor resolution"); - } - } - private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index f295ad77fc..096e1a1a46 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -1,690 +1,39 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; -import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; -import net.firedevops.firemud.gamedesign.dto.VersionDto; -import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; -import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; -import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final UUID NIL_UUID = new UUID(0L, 0L); private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; private final TemplateRemapSetService templateRemapSetService; - private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final ObjectMapper objectMapper; - @Value("${firemud.grpc.workload-namespace:}") - private String workloadNamespace; - @Override - @Transactional(noRollbackFor = FrozenLaunchDescriptorDenialException.class) @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - AuthoredWorldLaunchDescriptorEvidence.Request request) { - requireConfiguredNamespace(request.targetNamespace()); - launchDescriptorRepository.lockBoundRequest( - workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); - String requestJson = writeJson(request); - - Optional stored = - launchDescriptorRepository.findBoundByRequest( - workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); - if (stored.isPresent()) { - LaunchDescriptor descriptor = stored.orElseThrow(); - requireStoredRequestMatches(descriptor, request, requestJson); - AuthoredWorldSourceEvidence source = readExactSource(request); - String sourceJson = writeJson(source); - if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { - throwStoredFailure( - descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); - } - if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { - throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); - } - return readStored(descriptor, request, requestJson, sourceJson); - } - AuthoredWorldSourceEvidence source = readExactSource(request); - String sourceJson = writeJson(source); - if (launchDescriptorRepository - .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) - .isPresent()) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: retained private-owner request history is unbound or bound to another canonical identity"); - } - - try { - return resolveNewLaunchDescriptor(request, source, requestJson, sourceJson); - } catch (FrozenLaunchDescriptorDenialException denial) { - LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); - LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); - throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); - throw new IllegalStateException("Persisted deterministic launch denial was not returned"); - } - } - - private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( - AuthoredWorldLaunchDescriptorEvidence.Request request, - AuthoredWorldSourceEvidence source, - String requestJson, - String sourceJson) { - GameTemplateLaunchConfigView template = - gameTemplateRepository - .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) - .filter(row -> row.getId() == request.gameTemplateId()) - .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) - .orElseThrow( - () -> - denial( - "INVALID_TEMPLATE_CONFIGURATION", - "template is not owned by the source game")); - if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw denial( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); - } - Long versionId = - request.targetVersionIdPresent() - ? request.targetVersionId() - : template.getDefaultVersionId(); - if (versionId == null || versionId <= 0) { - throw denial("INVALID_TEMPLATE_CONFIGURATION", "template defaultVersionId is required"); - } - VersionDto version = - versionRepository - .findById(versionId) - .filter(row -> row.getId().equals(versionId)) - .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) - .map( - row -> - new VersionDto( - row.getId(), - row.getTenantId(), - row.getVersionNumber(), - row.getVersionState(), - row.getVersionStateEpoch(), - row.getScriptPatchVersion(), - row.getBaseVersionId(), - row.isScriptOnly(), - row.getNotes(), - row.getCreatedAt(), - row.getUpdatedAt())) - .orElseThrow( - () -> - denial( - "INVALID_TEMPLATE_CONFIGURATION", - "target version is not owned by the source game")); - if (version.versionState() != VersionLifecycleState.PUBLISHED - && version.versionState() != VersionLifecycleState.ACTIVE) { - throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); - } - requireReadyScriptPatch( - request.requestedScriptPatchVersionPresent() - ? request.requestedScriptPatchVersion() - : null); - requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); - requireReadyScriptPatch(version.scriptPatchVersion()); - String scriptPatch = resolveScriptPatchVersion(template, request, version); - String runtimeFlags = resolveRuntimeFlagsJson(template, request); - - String remapSetId = null; - if (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { - TemplateRemapSetDto remap = - templateRemapSetService - .findApprovedTemplateRemapSet( - source.sourceGameTenantKey(), request.sourceVersionId(), versionId) - .orElseThrow( - () -> - denial( - "LAUNCH_REMAP_REQUIRED", - "replacement-instance launch requires an approved remapSetId")); - remapSetId = remap.remapSetId(); - } - PublishedReleaseBundleDto bundle = - requirePublishedReleaseBundle(source.sourceGameTenantKey(), versionId); - if (!source.sourceGameTenantKey().equals(bundle.tenantId()) - || !Objects.equals(bundle.versionId(), versionId)) { - throw denial( - "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); - } - try { - PublishedReleaseBundleContract.requireSupportedSchemaForLaunchDescriptor(bundle); - } catch (IllegalArgumentException invalid) { - if (invalid.getMessage() != null - && invalid - .getMessage() - .startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED + ":")) { - throw denial( - PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, - "unsupported published release bundle attestation schema " - + bundle.attestationSchemaVersion()); - } - throw invalid; - } - if (bundle.publishedReleaseBundleRef() == null - || bundle.publishedReleaseBundleRef().isBlank()) { - throw denial( - "RELEASE_BUNDLE_NOT_FOUND", "published release bundle has no persisted opaque reference"); - } - - String descriptorId = "ld-" + UUID.randomUUID(); - AuthoredWorldLaunchDescriptorEvidence evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - request, - descriptorId, - versionId, - scriptPatch != null, - scriptPatch, - runtimeFlags, - bundle.generationConfigRevision(), - version.versionStateEpoch(), - bundle.id(), - bundle.publishedReleaseBundleRef(), - remapSetId != null, - remapSetId); - LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId(descriptorId); - descriptor.setTenantId(source.sourceGameTenantKey()); - descriptor.setGameTemplateId(request.gameTemplateId()); - descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); - descriptor.setRequestHash(evidence.requestDigest()); - descriptor.setVersionId(versionId); - descriptor.setScriptPatchVersion(scriptPatch); - descriptor.setRuntimeFlagsJson(runtimeFlags); - descriptor.setGenerationConfigRevision(bundle.generationConfigRevision()); - descriptor.setVersionStateEpoch(version.versionStateEpoch()); - descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); - descriptor.setRemapSetId(remapSetId); - descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); - descriptor.setTargetNamespace(workloadNamespace); - descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); - descriptor.setWorldSlug(request.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - request.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); - descriptor.setRequestDigest(evidence.requestDigest()); - descriptor.setResultDigest(evidence.resultDigest()); - descriptor.setOriginalRequestJson(requestJson); - descriptor.setSourceEvidenceJson(sourceJson); - return readStored( - launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); - } - - @Override - @Transactional(readOnly = true) - @Timed(value = "gamedesign.launchDescriptor.read") - public ResolvedLaunchDescriptorDto getLaunchDescriptor( - UUID readRequestId, - UUID canonicalTenantId, - String worldSlug, - String controlPlaneRequestId, - String expectedRequestDigest, - String expectedResultDigest) { - DescriptorReadContext context = - findExactSuccessfulDescriptor( - readRequestId, - canonicalTenantId, - worldSlug, - controlPlaneRequestId, - expectedRequestDigest, - expectedResultDigest); - LaunchDescriptor descriptor = context.descriptor(); - AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); - AuthoredWorldSourceEvidence source = readExactSource(storedRequest); - String sourceJson = writeJson(source); - if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); - } - return readStored( - descriptor, - storedRequest, - descriptor.getOriginalRequestJson(), - descriptor.getSourceEvidenceJson()); - } - - @Override - @Transactional(propagation = Propagation.MANDATORY, readOnly = true) - @Timed(value = "gamedesign.launchDescriptor.readOwnerSnapshot") - public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( - UUID readRequestId, - UUID canonicalTenantId, - String worldSlug, - String controlPlaneRequestId, - String expectedRequestDigest, - String expectedResultDigest) { - requireOwnerSnapshot(); - DescriptorReadContext context = - findExactSuccessfulDescriptor( - readRequestId, - canonicalTenantId, - worldSlug, - controlPlaneRequestId, - expectedRequestDigest, - expectedResultDigest); - LaunchDescriptor descriptor = context.descriptor(); - AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); - var sourceSnapshot = - authoredWorldSourceRepository - .readVersionStateSnapshot( - workloadNamespace, - readRequestId, - canonicalTenantId, - worldSlug, - storedRequest.authoredWorldSourceOperationId(), - storedRequest.authoredWorldSourceEvidenceDigest(), - Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) - .orElseThrow( - () -> - new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); - AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); - requireExactSource(storedRequest, source); - String sourceJson = writeJson(source); - if (!sourceJson.equals(descriptor.getSourceEvidenceJson()) - || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId())) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); - } - return readStored( - descriptor, - storedRequest, - descriptor.getOriginalRequestJson(), - descriptor.getSourceEvidenceJson()); - } - - private DescriptorReadContext findExactSuccessfulDescriptor( - UUID readRequestId, - UUID canonicalTenantId, - String worldSlug, + String tenantId, + long gameTemplateId, String controlPlaneRequestId, - String expectedRequestDigest, - String expectedResultDigest) { - if (readRequestId == null || NIL_UUID.equals(readRequestId)) { - throw new IllegalArgumentException("Canonical nonnil read request ID is required"); - } - requireConfiguredNamespace(workloadNamespace); - AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); - if (controlPlaneRequestId == null - || controlPlaneRequestId.isBlank() - || !GameTenantCreationDigest.isDigest(expectedRequestDigest) - || !GameTenantCreationDigest.isDigest(expectedResultDigest)) { - throw new IllegalArgumentException("Exact descriptor read selector and digests are required"); - } - LaunchDescriptor descriptor = - launchDescriptorRepository - .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) - .orElseThrow( - () -> - new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); - if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); - } - if (descriptor.getDescriptorSchemaVersion() == null) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_UNBOUND: retained descriptor history has no authored-world binding"); - } - if (!worldSlug.equals(descriptor.getWorldSlug()) - || !canonicalTenantId.toString().equals(descriptor.getCanonicalTenantId()) - || !expectedRequestDigest.equals(descriptor.getRequestDigest()) - || !expectedResultDigest.equals(descriptor.getResultDigest())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match"); - } - AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = - readRequest(descriptor.getOriginalRequestJson()); - return new DescriptorReadContext(descriptor, storedRequest); - } - - private AuthoredWorldSourceEvidence readExactSource( - AuthoredWorldLaunchDescriptorEvidence.Request request) { - AuthoredWorldSourceEvidence source = - authoredWorldSourceRepository - .read( - request.authoredWorldSourceOperationId(), - request.canonicalTenantId(), - request.worldSlug(), - workloadNamespace) - .orElseThrow( - () -> - new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); - requireExactSource(request, source); - return source; - } - - private void requireExactSource( - AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { - if (!workloadNamespace.equals(source.targetNamespace()) - || !request.canonicalTenantId().equals(source.canonicalTenantId()) - || !request.worldSlug().equals(source.worldSlug()) - || !request.authoredWorldSourceOperationId().equals(source.operationId()) - || !request.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest())) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); - } - } - - private void requireOwnerSnapshot() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) - .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { - throw new IllegalStateException( - "Launch descriptor snapshot read requires a read-only REPEATABLE_READ owner snapshot"); - } - } - - private record DescriptorReadContext( - LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) {} - - private ResolvedLaunchDescriptorDto readStored( - LaunchDescriptor descriptor, - AuthoredWorldLaunchDescriptorEvidence.Request request, - String requestJson, - String sourceJson) { - if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) - || descriptor.getFailureCode() != null - || descriptor.getFailureMessage() != null - || descriptor.getDescriptorSchemaVersion() == null - || !Objects.equals( - descriptor.getDescriptorSchemaVersion(), - AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) - || !workloadNamespace.equals(descriptor.getTargetNamespace()) - || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) - || !request.worldSlug().equals(descriptor.getWorldSlug()) - || !request - .authoredWorldSourceOperationId() - .toString() - .equals(descriptor.getAuthoredWorldSourceOperationId()) - || !request - .authoredWorldSourceEvidenceDigest() - .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) - || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) - || request.gameTemplateId() != descriptor.getGameTemplateId() - || !requestJson.equals(descriptor.getOriginalRequestJson()) - || !sourceJson.equals(descriptor.getSourceEvidenceJson()) - || !request.requestDigest().equals(descriptor.getRequestHash()) - || !request.requestDigest().equals(descriptor.getRequestDigest())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request"); - } - AuthoredWorldLaunchDescriptorEvidence evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - request, - descriptor.getLaunchDescriptorId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion() != null, - descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId() != null, - descriptor.getRemapSetId()); - evidence.requireValid(); - if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); - } - return new ResolvedLaunchDescriptorDto( - evidence.launchDescriptorId(), - evidence.canonicalTenantId().toString(), - evidence.gameTemplateId(), - evidence.controlPlaneRequestId(), - evidence.versionId(), - evidence.scriptPatchVersion(), - evidence.runtimeFlagsJson(), - evidence.generationConfigRevision(), - evidence.versionStateEpoch(), - evidence.releaseBundleId(), - evidence.publishedReleaseBundleRef(), - evidence.remapSetId(), - evidence); - } - - private LaunchDescriptor frozenFailure( - AuthoredWorldLaunchDescriptorEvidence.Request request, - AuthoredWorldSourceEvidence source, - String requestJson, - String sourceJson, - FrozenLaunchDescriptorDenialException denial) { - LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setTenantId(source.sourceGameTenantKey()); - descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); - descriptor.setRequestHash(request.requestDigest()); - descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); - descriptor.setTargetNamespace(workloadNamespace); - descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); - descriptor.setWorldSlug(request.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - request.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); - descriptor.setRequestDigest(request.requestDigest()); - descriptor.setOriginalRequestJson(requestJson); - descriptor.setSourceEvidenceJson(sourceJson); - descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); - descriptor.setFailureCode(denial.failureCode()); - descriptor.setFailureMessage(denial.getMessage()); - return descriptor; - } - - private void requireStoredRequestMatches( - LaunchDescriptor descriptor, - AuthoredWorldLaunchDescriptorEvidence.Request request, - String requestJson) { - if (!workloadNamespace.equals(descriptor.getTargetNamespace()) - || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) - || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) - || !request.requestDigest().equals(descriptor.getRequestDigest()) - || !request.requestDigest().equals(descriptor.getRequestHash()) - || !requestJson.equals(descriptor.getOriginalRequestJson())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input"); - } - } - - private void throwStoredFailure( - LaunchDescriptor descriptor, - AuthoredWorldLaunchDescriptorEvidence.Request request, - String requestJson, - String sourceJson, - String sourceGameTenantKey) { - if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) - || !Objects.equals( - descriptor.getDescriptorSchemaVersion(), - AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) - || !workloadNamespace.equals(descriptor.getTargetNamespace()) - || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) - || !request.worldSlug().equals(descriptor.getWorldSlug()) - || !request - .authoredWorldSourceOperationId() - .toString() - .equals(descriptor.getAuthoredWorldSourceOperationId()) - || !request - .authoredWorldSourceEvidenceDigest() - .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) - || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) - || !request.requestDigest().equals(descriptor.getRequestDigest()) - || !request.requestDigest().equals(descriptor.getRequestHash()) - || !requestJson.equals(descriptor.getOriginalRequestJson()) - || !sourceJson.equals(descriptor.getSourceEvidenceJson()) - || !sourceGameTenantKey.equals(descriptor.getTenantId()) - || descriptor.getLaunchDescriptorId() != null - || descriptor.getGameTemplateId() != null - || descriptor.getVersionId() != null - || descriptor.getScriptPatchVersion() != null - || descriptor.getRuntimeFlagsJson() != null - || descriptor.getGenerationConfigRevision() != null - || descriptor.getVersionStateEpoch() != null - || descriptor.getReleaseBundleId() != null - || descriptor.getPublishedReleaseBundleRef() != null - || descriptor.getRemapSetId() != null - || descriptor.getResultDigest() != null - || !isPersistableFailureCode(descriptor.getFailureCode()) - || descriptor.getFailureMessage() == null - || descriptor.getFailureMessage().isBlank()) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_CONFLICT: stored failure is not the exact immutable request outcome"); - } - throw FrozenLaunchDescriptorDenialException.fromStored( - descriptor.getFailureCode(), descriptor.getFailureMessage()); - } - - private boolean isPersistableFailureCode(String failureCode) { - return switch (failureCode == null ? "" : failureCode) { - case "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", - PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED -> - true; - default -> false; - }; - } - - private static FrozenLaunchDescriptorDenialException denial(String code, String detail) { - return FrozenLaunchDescriptorDenialException.create(code, detail); - } - - private AuthoredWorldLaunchDescriptorEvidence.Request readRequest(String json) { - if (json == null) { - throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_UNBOUND: original request is missing"); - } - try { - AuthoredWorldLaunchDescriptorEvidence.Request request = - objectMapper.readValue(json, AuthoredWorldLaunchDescriptorEvidence.Request.class); - if (!writeJson(request).equals(json)) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_UNBOUND: original request is not the closed owner encoding"); - } - return request; - } catch (Exception exception) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_UNBOUND: original request is unreadable", exception); - } - } - - private String writeJson(Object value) { - try { - return objectMapper.writeValueAsString(value); - } catch (Exception exception) { - throw new IllegalStateException( - "Launch descriptor evidence could not be serialized", exception); - } - } - - private void requireConfiguredNamespace(String requestNamespace) { - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) - || !workloadNamespace.equals(requestNamespace)) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_NAMESPACE_MISMATCH: configured workload namespace is required"); - } - } - - private String resolveScriptPatchVersion( - GameTemplateLaunchConfigView template, - AuthoredWorldLaunchDescriptorEvidence.Request request, - VersionDto version) { - String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = - request.requestedScriptPatchVersionPresent() - ? normalizeBlank(request.requestedScriptPatchVersion()) - : null; - if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw denial( - "SCRIPT_PATCH_OVERRIDE_CONFLICT", - "requested script patch conflicts with template default"); - } - String resolved = requested != null ? requested : templateDefault; - if (resolved != null - && version.scriptPatchVersion() != null - && !version.scriptPatchVersion().isBlank() - && !version.scriptPatchVersion().equals(resolved)) { - throw denial( - "SCRIPT_PATCH_NOT_READY", - "requested script patch is not published for the resolved version"); - } - return resolved; - } - - private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, - AuthoredWorldLaunchDescriptorEvidence.Request request) { - String templateFlags = - normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null - ? "{}" - : template.getDefaultRuntimeFlagsJson(); - String requested = - request.requestedRuntimeFlagsJsonPresent() - ? normalizeBlank(request.requestedRuntimeFlagsJson()) - : null; - if (requested == null) { - return templateFlags; - } - if (!"{}".equals(templateFlags)) { - throw denial( - "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); - } - return requested; - } - - private void requireReadyScriptPatch(String scriptPatchVersion) { - if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { - throw denial( - "SCRIPT_PATCH_NOT_READY", - "exact published-for-base and Automation READY evidence is unavailable"); - } - } - - private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { - try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); - } catch (PublishedReleaseBundleNotFoundException exception) { - throw denial( - "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); - } - } - - private static String normalizeBlank(String value) { - return value == null || value.isBlank() ? null : value; + String requestedScriptPatchVersion, + Long sourceVersionId, + Long targetVersionId, + String requestedRuntimeFlagsJson) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 4b83a38f23..7765a74313 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,63 +3,21 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.time.LocalDateTime; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; -import net.firedevops.firemud.gamedesign.entity.Game; -import net.firedevops.firemud.gamedesign.entity.GameTemplate; -import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; -import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; -import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; -import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; -import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; -import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.exception.DataAccessException; -import org.jooq.impl.DSL; +import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; -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; @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -68,7 +26,6 @@ "spring.profiles.active=test", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", - "firemud.grpc.workload-namespace=launch-descriptor-test", "spring.grpc.server.port=0", "asset.store.endpoint=http://localhost:9000", "asset.store.bucket=test-bucket", @@ -78,20 +35,9 @@ }) @Import(NoGrpcServerTestConfiguration.class) class LaunchDescriptorServiceIntegrationTest { - private static final String NAMESPACE = "launch-descriptor-test"; - private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; - private static final org.jooq.Table LAUNCH_DESCRIPTOR = - DSL.table(DSL.name("launch_descriptor")); - private static final org.jooq.Field LAUNCH_ROW_ID = DSL.field(DSL.name("id"), Long.class); - private static final org.jooq.Field LAUNCH_NAMESPACE = - DSL.field(DSL.name("target_namespace"), String.class); - private static final org.jooq.Field LAUNCH_CANONICAL_TENANT = - DSL.field(DSL.name("canonical_tenant_id"), UUID.class); - private static final org.jooq.Field LAUNCH_REQUEST_ID = - DSL.field(DSL.name("control_plane_request_id"), String.class); - @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { @@ -100,999 +46,20 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; - @Autowired private GameRepository gameRepository; - @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; - @Autowired private GameTemplateRepository gameTemplateRepository; - @Autowired private VersionRepository versionRepository; - @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; - @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; @Autowired private LaunchDescriptorRepository launchDescriptorRepository; - @Autowired private PlatformTransactionManager transactionManager; - @Autowired private DSLContext dsl; - - @Test - void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange() { - Fixture fixture = fixture("cp-persisted"); - - ResolvedLaunchDescriptorDto original = - launchDescriptorService.resolveLaunchDescriptor(fixture.request()); - String generationConfigRevision = fixture.bundle().getGenerationConfigRevision(); - assertThat(generationConfigRevision.length()).isGreaterThan(128); - assertThat(original.generationConfigRevision()).isEqualTo(generationConfigRevision); - assertThat(original.gameTemplateId()).isEqualTo(fixture.template().getId()); - assertThat(original.versionId()).isEqualTo(fixture.version().getId()); - assertThat(original.versionStateEpoch()).isEqualTo(1L); - assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); - assertThat(original.publishedReleaseBundleRef()) - .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); - assertThat( - publishedReleaseBundleRepository - .findByTenantIdAndVersionId( - fixture.privateSourceTenantKey(), fixture.version().getId()) - .orElseThrow() - .getPublishedReleaseBundleRef()) - .isEqualTo(original.publishedReleaseBundleRef()); - assertThat(original.authoredWorldBinding()).isNotNull(); - assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) - .isEqualTo(fixture.source().operationId()); - assertThat(original.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) - .isEqualTo(fixture.source().evidenceDigest()); - assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); - - Version newDraft = new Version(); - newDraft.setTenantId(fixture.privateSourceTenantKey()); - newDraft.setVersionNumber(2); - newDraft.setVersionState(VersionLifecycleState.DRAFT); - newDraft.setVersionStateEpoch(1L); - newDraft.setNotes("new mutable template default"); - newDraft.setUpdatedAt(LocalDateTime.now()); - newDraft = versionRepository.save(newDraft); - fixture.template().setDefaultVersionId(newDraft.getId()); - gameTemplateRepository.save(fixture.template()); - fixture.version().setVersionState(VersionLifecycleState.RETIRED); - fixture.version().setVersionStateEpoch(2L); - versionRepository.save(fixture.version()); - - ResolvedLaunchDescriptorDto retry = - launchDescriptorService.resolveLaunchDescriptor(fixture.request()); - - assertThat(retry).isEqualTo(original); - assertThat(retry.versionId()).isEqualTo(fixture.version().getId()); - LaunchDescriptor persisted = - launchDescriptorRepository - .findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) - .orElseThrow(); - assertThat(persisted.getLaunchDescriptorId()).isEqualTo(original.launchDescriptorId()); - assertThat(persisted.getRequestDigest()) - .isEqualTo(original.authoredWorldBinding().requestDigest()); - assertThat(persisted.getResultDigest()) - .isEqualTo(original.authoredWorldBinding().resultDigest()); - assertThat(persisted.getPublishedReleaseBundleRef()) - .isEqualTo(original.publishedReleaseBundleRef()); - assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); - assertThat( - dsl.fetchCount( - LAUNCH_DESCRIPTOR, - LAUNCH_NAMESPACE - .eq(NAMESPACE) - .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) - .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) - .isEqualTo(1); - - ResolvedLaunchDescriptorDto readback = - launchDescriptorService.getLaunchDescriptor( - UUID.randomUUID(), - fixture.canonicalTenantId(), - fixture.source().worldSlug(), - fixture.controlPlaneRequestId(), - original.authoredWorldBinding().requestDigest(), - original.authoredWorldBinding().resultDigest()); - assertThat(readback).isEqualTo(original); - } - - @Test - void concurrentExactRetriesPersistOneOriginalDescriptor() throws Exception { - Fixture fixture = fixture("cp-concurrent"); - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future first = - executor.submit(() -> resolveAfterLatch(fixture, ready, start)); - Future second = - executor.submit(() -> resolveAfterLatch(fixture, ready, start)); - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - - ResolvedLaunchDescriptorDto firstResult = first.get(20, TimeUnit.SECONDS); - ResolvedLaunchDescriptorDto secondResult = second.get(20, TimeUnit.SECONDS); - - assertThat(secondResult).isEqualTo(firstResult); - assertThat( - dsl.fetchCount( - LAUNCH_DESCRIPTOR, - LAUNCH_NAMESPACE - .eq(NAMESPACE) - .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) - .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) - .isEqualTo(1); - LaunchDescriptor persisted = - launchDescriptorRepository - .findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) - .orElseThrow(); - assertThat(persisted.getLaunchDescriptorId()).isEqualTo(firstResult.launchDescriptorId()); - assertThat(persisted.getResultDigest()) - .isEqualTo(firstResult.authoredWorldBinding().resultDigest()); - } finally { - start.countDown(); - executor.shutdownNow(); - } - } @Test - void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries() - throws Exception { - Fixture fixture = fixture("cp-frozen-phase"); - fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); - gameTemplateRepository.save(fixture.template()); - - assertThatThrownBy(() -> launchDescriptorService.resolveLaunchDescriptor(fixture.request())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); - - LaunchDescriptor failed = - launchDescriptorRepository - .findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) - .orElseThrow(); - assertThat(failed.getOutcomeStatus()).isEqualTo(LaunchDescriptor.OUTCOME_FAILED); - assertThat(failed.getFailureCode()).isEqualTo("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); - assertThat(failed.getFailureMessage()) - .isEqualTo( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); - assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); - assertThat(failed.getOriginalRequestJson()).isNotBlank(); - assertThat(failed.getSourceEvidenceJson()).isNotBlank(); - assertThat(failed.getLaunchDescriptorId()).isNull(); - assertThat(failed.getGameTemplateId()).isNull(); - assertThat(failed.getVersionId()).isNull(); - assertThat(failed.getReleaseBundleId()).isNull(); - assertThat(failed.getResultDigest()).isNull(); - assertFailedShapeRejected(failed, "cp-frozen-null-schema", true); - assertFailedShapeRejected(failed, "cp-frozen-null-failure-code", false); - assertThat( - dsl.fetchCount( - LAUNCH_DESCRIPTOR, - LAUNCH_NAMESPACE - .eq(NAMESPACE) - .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) - .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) - .isEqualTo(1); - - fixture.template().setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); - gameTemplateRepository.save(fixture.template()); - - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future first = executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); - Future second = - executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); - assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); - } finally { - start.countDown(); - executor.shutdownNow(); - } - + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { assertThatThrownBy( () -> launchDescriptorService.resolveLaunchDescriptor( - fixture.requestWithPatch("different-patch"))) + "1", 9L, "integration-cp-unbound", null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("control-plane request identity was reused with changed input"); - - ResolvedLaunchDescriptorDto freshAttempt = - launchDescriptorService.resolveLaunchDescriptor(fixture.request("cp-frozen-phase-fresh")); - assertThat(freshAttempt.versionId()).isEqualTo(fixture.version().getId()); - assertThat( - launchDescriptorRepository - .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), "cp-frozen-phase-fresh") - .orElseThrow() - .getOutcomeStatus()) - .isEqualTo(LaunchDescriptor.OUTCOME_SUCCESS); - } - - @Test - void corruptFailureReadbackRollsBackTheOutcomeInsert() { - Fixture fixture = fixture("cp-corrupt-failure-readback"); - fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); - gameTemplateRepository.save(fixture.template()); - LaunchDescriptorRepository corruptingRepository = - new LaunchDescriptorRepository(dsl) { - @Override - public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { - LaunchDescriptor persisted = super.insertImmutable(descriptor); - persisted.setFailureCode("UNRECOGNIZED_FAILURE"); - return persisted; - } - }; - LaunchDescriptorServiceImpl corruptingService = - new LaunchDescriptorServiceImpl( - gameTemplateRepository, - corruptingRepository, - versionRepository, - Mockito.mock(PublishedReleaseBundleService.class), - Mockito.mock(TemplateRemapSetService.class), - authoredWorldSourceRepository, - new ObjectMapper()); - ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); - TransactionTemplate transaction = new TransactionTemplate(transactionManager); - - assertThatThrownBy( - () -> - transaction.execute( - status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("stored failure is not the exact immutable request outcome"); - - assertThat( - launchDescriptorRepository.findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) - .isEmpty(); - } - - @Test - void concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome() throws Exception { - Fixture fixture = fixture("cp-mixed-candidates"); - CountDownLatch lockArrivals = new CountDownLatch(2); - CountDownLatch viewReached = new CountDownLatch(1); - CountDownLatch continueResolution = new CountDownLatch(1); - LaunchDescriptorRepository serializedRepository = - new LaunchDescriptorRepository(dsl) { - @Override - public void lockBoundRequest(String targetNamespace, UUID tenantId, String requestId) { - lockArrivals.countDown(); - super.lockBoundRequest(targetNamespace, tenantId, requestId); - } - }; - LaunchDescriptorServiceImpl failureCandidate = - candidateForPhase( - fixture, - serializedRepository, - TemplateReferencePhase.LEGACY, - viewReached, - continueResolution); - LaunchDescriptorServiceImpl successCandidate = - candidateForPhase( - fixture, - serializedRepository, - TemplateReferencePhase.ENFORCED, - viewReached, - continueResolution); - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future first = - executor.submit( - () -> resolveCandidateInOwnerTransaction(failureCandidate, fixture, ready, start)); - Future second = - executor.submit( - () -> resolveCandidateInOwnerTransaction(successCandidate, fixture, ready, start)); - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - assertThat(viewReached.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(lockArrivals.await(10, TimeUnit.SECONDS)).isTrue(); - continueResolution.countDown(); - - String firstResult = first.get(20, TimeUnit.SECONDS); - String secondResult = second.get(20, TimeUnit.SECONDS); - assertThat(secondResult).isEqualTo(firstResult); - LaunchDescriptor stored = - launchDescriptorRepository - .findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) - .orElseThrow(); - assertThat(stored.getOutcomeStatus()) - .isEqualTo( - firstResult.startsWith("FAILED:") - ? LaunchDescriptor.OUTCOME_FAILED - : LaunchDescriptor.OUTCOME_SUCCESS); - assertThat( - dsl.fetchCount( - LAUNCH_DESCRIPTOR, - LAUNCH_NAMESPACE - .eq(NAMESPACE) - .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) - .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) - .isEqualTo(1); - } finally { - continueResolution.countDown(); - start.countDown(); - executor.shutdownNow(); - } - } - - @Test - void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { - Fixture fixture = fixture("cp-rollback"); - AuthoredWorldLaunchDescriptorEvidence evidence = evidence(fixture, "ld-rollback-candidate"); - LaunchDescriptor candidate = entity(evidence, fixture); - TransactionTemplate transaction = new TransactionTemplate(transactionManager); - - assertThatThrownBy( - () -> - transaction.execute( - status -> { - launchDescriptorRepository.insertImmutable(candidate); - throw new IllegalStateException("force owner transaction rollback"); - })) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("force owner transaction rollback"); - - assertThat( - launchDescriptorRepository.findBoundByRequest( - NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) - .isEmpty(); - assertThat( - launchDescriptorRepository.findByPrivateRequest( - fixture.privateSourceTenantKey(), fixture.controlPlaneRequestId())) - .isEmpty(); - ResolvedLaunchDescriptorDto committed = - launchDescriptorService.resolveLaunchDescriptor(fixture.request()); - assertThat(committed.authoredWorldBinding().requestDigest()) - .isEqualTo(evidence.requestDigest()); - } - - @Test - void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { - String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); - DriverManagerDataSource dataSource = isolatedDataSource(schema); - migrate(dataSource, schema, MigrationVersion.fromVersion("34")); - DSLContext isolatedDsl = - DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - DataSourceTransactionManager isolatedTransactionManager = - new DataSourceTransactionManager(dataSource); - TransactionTemplate isolatedTransaction = new TransactionTemplate(isolatedTransactionManager); - - String privateTenantKey = privateTenantKey(); - Game game = new Game(); - game.setTenantId(privateTenantKey); - game.setName("Retained launch source"); - game.setDescription("Persisted V34 source fixture"); - Game persistedGame = - isolatedTransaction.execute(status -> new GameRepository(isolatedDsl).save(game)); - assertThat(persistedGame).isNotNull(); - String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); - AuthoredWorldSourceEvidence source = - seedPreV41AuthoredWorldSource( - isolatedDsl, - isolatedTransaction, - persistedGame, - UUID.randomUUID(), - "tenant-" + suffix, - "world-" + suffix, - "Retained World 🐉"); - assertThat(source).isNotNull(); - - Long versionId = - isolatedDsl - .resultQuery( - "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch) " - + "VALUES (?, 1, 'PUBLISHED', 1) RETURNING id", - privateTenantKey) - .fetchOne(0, Long.class); - Long templateId = - isolatedDsl - .resultQuery( - "INSERT INTO game_templates (tenant_id, name, config) " - + "VALUES (?, ?, '{}'::jsonb) RETURNING id", - privateTenantKey, - "Retained Template " + suffix) - .fetchOne(0, Long.class); - // Synthetic retained-row seed for storage compatibility only; not live publication proof. - Long bundleId = - isolatedDsl - .resultQuery( - "INSERT INTO published_release_bundle " - + "(tenant_id, version_id, version_number, attestation_schema_version, " - + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " - + "participant_digests_json, generation_config_revision) " - + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", - privateTenantKey, - versionId, - "synthetic-retained-fixture-" + suffix, - "sha256:" + "d".repeat(64), - "gen-rev:" + suffix) - .fetchOne(0, Long.class); - if (bundleId == null) { - throw new IllegalStateException("Retained V34 release bundle insertion returned no identity"); - } - String requestId = "retained-cp-" + suffix; - String legacyDescriptorId = "ld-retained-" + suffix; - isolatedDsl.execute( - "INSERT INTO launch_descriptor " - + "(launch_descriptor_id, tenant_id, game_template_id, control_plane_request_id, " - + "request_hash, version_id, runtime_flags_json, generation_config_revision, " - + "version_state_epoch, release_bundle_id, published_release_bundle_ref) " - + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?)", - legacyDescriptorId, - privateTenantKey, - templateId, - requestId, - "legacy-request-hash-" + suffix, - versionId, - "gen-rev:" + suffix, - bundleId, - "legacy-release-ref-" + suffix); - Map retainedV34Snapshot = - legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); - Map retainedBundleSnapshot = - retainedReleaseBundleSnapshot(isolatedDsl, bundleId); - - migrate(dataSource, schema, null); - LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); - var retainedBundleReference = - isolatedDsl.fetchOne( - "SELECT published_release_bundle_ref FROM published_release_bundle WHERE id = ?", - bundleId); - if (retainedBundleReference == null) { - throw new IllegalStateException("Retained V34 release bundle reference row is missing"); - } - assertThat(retainedBundleReference.get("published_release_bundle_ref", String.class)).isNull(); - assertThat(retainedReleaseBundleSnapshot(isolatedDsl, bundleId)) - .isEqualTo(retainedBundleSnapshot); - assertThat( - new PublishedReleaseBundleRepository(isolatedDsl) - .findByTenantIdAndVersionId(privateTenantKey, versionId) - .orElseThrow() - .getPublishedReleaseBundleRef()) - .isNull(); - assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) - .isEqualTo(retainedV34Snapshot); - LaunchDescriptor before = - launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow(); - assertThat(before.getDescriptorSchemaVersion()).isNull(); - assertThat(before.getCanonicalTenantId()).isNull(); - assertThat(before.getRequestHash()).isEqualTo("legacy-request-hash-" + suffix); - - AuthoredWorldLaunchDescriptorEvidence.Request request = - new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - requestId, - persistedGame.getCanonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - templateId, - false, - null, - false, - null, - false, - null, - false, - null); - LaunchDescriptorServiceImpl isolatedService = - new LaunchDescriptorServiceImpl( - Mockito.mock(GameTemplateRepository.class), - launchRepository, - Mockito.mock(VersionRepository.class), - Mockito.mock(PublishedReleaseBundleService.class), - Mockito.mock(TemplateRemapSetService.class), - new GameAuthoredWorldSourceRepository(isolatedDsl), - new ObjectMapper()); - ReflectionTestUtils.setField(isolatedService, "workloadNamespace", NAMESPACE); + .hasMessage( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); - assertThatThrownBy(() -> isolatedService.resolveLaunchDescriptor(request)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("LAUNCH_DESCRIPTOR_CONFLICT") - .hasMessageContaining("unbound"); - assertThat( - launchRepository.findBoundByRequest( - NAMESPACE, persistedGame.getCanonicalTenantId(), requestId)) + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) .isEmpty(); - assertRetainedRowUnchanged( - before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); - - assertThatThrownBy( - () -> - isolatedDsl.execute( - "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", - "{\"changed\":true}", - before.getId())) - .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("launch descriptors are immutable"); - assertRetainedRowUnchanged( - before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); - } - - private Fixture fixture(String controlPlaneRequestId) { - String privateTenantKey = privateTenantKey(); - Game sourceGame = new Game(); - sourceGame.setTenantId(privateTenantKey); - sourceGame.setName("Launch Source " + UUID.randomUUID()); - sourceGame.setDescription("Persisted fresh Game Design tenant source"); - Game persistedGame = - new TransactionTemplate(transactionManager) - .execute(status -> gameRepository.save(sourceGame)); - assertThat(persistedGame).isNotNull(); - - String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); - AuthoredWorldSourceEvidence source = - new TransactionTemplate(transactionManager) - .execute( - status -> - authoredWorldSourceRepository.register( - NAMESPACE, - UUID.randomUUID(), - persistedGame.getCanonicalTenantId(), - "tenant-" + suffix, - "world-" + suffix, - "Launch World 🐉")); - assertThat(source).isNotNull(); - - Version version = new Version(); - version.setTenantId(privateTenantKey); - version.setVersionNumber(1); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(1L); - version.setNotes("synthetic release storage proof fixture"); - version.setUpdatedAt(LocalDateTime.now()); - version = versionRepository.save(version); - - GameTemplate template = new GameTemplate(); - template.setTenantId(privateTenantKey); - template.setName("Launch Template " + suffix); - template.setDescription("Persisted descriptor resolution fixture"); - template.setConfig("{}"); - template.setDefaultVersionId(version.getId()); - template.setDefaultRuntimeFlagsJson("{}"); - template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); - template = gameTemplateRepository.save(template); - - // This row exercises descriptor storage and resolution only; it is not live publication proof. - PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId(privateTenantKey); - bundle.setVersionId(version.getId()); - bundle.setVersionNumber(1); - bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); - bundle.setManifestHash("sha256:" + "e".repeat(64)); - bundle.setGenerationConfigRevision("gen-rev:" + suffix + ":" + "g".repeat(180)); - bundle.setRequiredManifestAssetKeysJson("[]"); - bundle.setParticipantDigestsJson("[]"); - bundle.setScriptOnly(false); - bundle = publishedReleaseBundleRepository.save(bundle); - - return new Fixture( - controlPlaneRequestId, - persistedGame.getCanonicalTenantId(), - privateTenantKey, - source, - version, - template, - bundle); - } - - private void assertFailedShapeRejected( - LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { - assertThatThrownBy( - () -> - dsl.execute( - """ - INSERT INTO launch_descriptor ( - tenant_id, - control_plane_request_id, - request_hash, - descriptor_schema_version, - target_namespace, - canonical_tenant_id, - world_slug, - authored_world_source_operation_id, - authored_world_source_evidence_digest, - request_digest, - original_request_json, - source_evidence_json, - outcome_status, - failure_code, - failure_message) - VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, - CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) - """, - failed.getTenantId(), - controlPlaneRequestId, - failed.getRequestHash(), - nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), - failed.getTargetNamespace(), - failed.getCanonicalTenantId(), - failed.getWorldSlug(), - failed.getAuthoredWorldSourceOperationId(), - failed.getAuthoredWorldSourceEvidenceDigest(), - failed.getRequestDigest(), - failed.getOriginalRequestJson(), - failed.getSourceEvidenceJson(), - nullSchemaVersion ? failed.getFailureCode() : null, - failed.getFailureMessage())) - .isInstanceOf(DataIntegrityViolationException.class) - .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); - } - - private ResolvedLaunchDescriptorDto resolveAfterLatch( - Fixture fixture, CountDownLatch ready, CountDownLatch start) { - ready.countDown(); - await(start); - return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); - } - - private String resolveFailureAfterLatch( - Fixture fixture, CountDownLatch ready, CountDownLatch start) { - ready.countDown(); - await(start); - try { - launchDescriptorService.resolveLaunchDescriptor(fixture.request()); - return "unexpected success"; - } catch (IllegalArgumentException exception) { - return exception.getMessage(); - } - } - - private String resolveCandidateInOwnerTransaction( - LaunchDescriptorServiceImpl service, - Fixture fixture, - CountDownLatch ready, - CountDownLatch start) { - ready.countDown(); - await(start); - return new TransactionTemplate(transactionManager) - .execute( - status -> { - try { - return "SUCCESS:" - + service - .resolveLaunchDescriptor(fixture.request()) - .authoredWorldBinding() - .resultDigest(); - } catch (IllegalArgumentException exception) { - return "FAILED:" + exception.getMessage(); - } - }); - } - - private LaunchDescriptorServiceImpl candidateForPhase( - Fixture fixture, - LaunchDescriptorRepository repository, - TemplateReferencePhase phase, - CountDownLatch viewReached, - CountDownLatch continueResolution) { - GameTemplateRepository templateRepository = Mockito.mock(GameTemplateRepository.class); - GameTemplateLaunchConfigView view = Mockito.mock(GameTemplateLaunchConfigView.class); - Mockito.when(view.getId()).thenReturn(fixture.template().getId()); - Mockito.when(view.getTenantId()).thenReturn(fixture.privateSourceTenantKey()); - Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); - Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - Mockito.when(view.getTemplateReferencePhase()) - .thenAnswer( - invocation -> { - viewReached.countDown(); - await(continueResolution); - return phase; - }); - Mockito.when( - templateRepository.findLaunchConfigByTenantIdAndId( - fixture.privateSourceTenantKey(), fixture.template().getId())) - .thenReturn(java.util.Optional.of(view)); - LaunchDescriptorServiceImpl service = - new LaunchDescriptorServiceImpl( - templateRepository, - repository, - versionRepository, - publishedReleaseBundleService, - Mockito.mock(TemplateRemapSetService.class), - authoredWorldSourceRepository, - new ObjectMapper()); - ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); - return service; - } - - private void await(CountDownLatch latch) { - try { - if (!latch.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting for descriptor retry race"); - } - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting for descriptor retry race", exception); - } - } - - private AuthoredWorldLaunchDescriptorEvidence evidence(Fixture fixture, String descriptorId) { - return AuthoredWorldLaunchDescriptorEvidence.create( - fixture.request(), - descriptorId, - fixture.version().getId(), - false, - null, - "{}", - fixture.bundle().getGenerationConfigRevision(), - fixture.version().getVersionStateEpoch(), - fixture.bundle().getId(), - "release-bundle:" - + fixture.canonicalTenantId() - + ":" - + fixture.version().getId() - + ":" - + fixture.bundle().getId(), - false, - null); - } - - private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, Fixture fixture) { - LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); - descriptor.setTenantId(fixture.privateSourceTenantKey()); - descriptor.setGameTemplateId(evidence.gameTemplateId()); - descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); - descriptor.setRequestHash(evidence.requestDigest()); - descriptor.setVersionId(evidence.versionId()); - descriptor.setScriptPatchVersion(evidence.scriptPatchVersion()); - descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); - descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); - descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); - descriptor.setReleaseBundleId(evidence.releaseBundleId()); - descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); - descriptor.setRemapSetId(evidence.remapSetId()); - descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); - descriptor.setTargetNamespace(evidence.targetNamespace()); - descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); - descriptor.setWorldSlug(evidence.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - evidence.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); - descriptor.setRequestDigest(evidence.requestDigest()); - descriptor.setResultDigest(evidence.resultDigest()); - descriptor.setOriginalRequestJson(json(evidence.request())); - descriptor.setSourceEvidenceJson(json(fixture.source())); - return descriptor; - } - - private String json(Object value) { - try { - return new ObjectMapper().writeValueAsString(value); - } catch (Exception exception) { - throw new IllegalStateException("Test evidence serialization failed", exception); - } - } - - private DriverManagerDataSource isolatedDataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl(postgres.getJdbcUrl()); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - dataSource.setSchema(schema); - return dataSource; - } - - /** Seeds the immutable source/binding shape written before V41 added automatic delivery. */ - private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( - DSLContext isolatedDsl, - TransactionTemplate isolatedTransaction, - Game sourceGame, - UUID registrationRequestId, - String tenantSlug, - String worldSlug, - String worldDisplayName) { - UUID operationId = UUID.randomUUID(); - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - NAMESPACE, - registrationRequestId, - sourceGame.getCanonicalTenantId(), - tenantSlug, - worldSlug, - worldDisplayName); - String evidenceDigest = - AuthoredWorldSourceDigest.evidenceDigest( - NAMESPACE, - registrationRequestId, - operationId, - requestDigest, - sourceGame.getCanonicalTenantId(), - tenantSlug, - worldSlug, - worldDisplayName, - sourceGame.getId(), - sourceGame.getTenantId(), - "NEW_GAME_ROW"); - AuthoredWorldSourceEvidence source = - new AuthoredWorldSourceEvidence( - 1, - NAMESPACE, - registrationRequestId, - operationId, - requestDigest, - sourceGame.getCanonicalTenantId(), - tenantSlug, - worldSlug, - worldDisplayName, - sourceGame.getId(), - sourceGame.getTenantId(), - "NEW_GAME_ROW", - evidenceDigest); - - isolatedTransaction.execute( - status -> { - isolatedDsl.execute( - "INSERT INTO game_design_tenant_slug_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", - source.targetNamespace(), - source.canonicalTenantId(), - source.tenantSlug(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - isolatedDsl.execute( - "INSERT INTO game_design_authored_world_source_operations " - + "(operation_id, schema_version, target_namespace, registration_request_id, " - + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " - + "world_display_name, source_game_row_id, source_game_tenant_key, " - + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - source.operationId(), - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.requestDigest(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest()); - return null; - }); - return source; - } - - private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table(FLYWAY_TABLE) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); - if (target != null) { - configuration.target(target); - } - configuration.load().migrate(); - } - - private Map legacyLaunchDescriptorSnapshot( - DSLContext isolatedDsl, String privateTenantKey, String controlPlaneRequestId) { - var record = - isolatedDsl.fetchOne( - "SELECT id, launch_descriptor_id, tenant_id, game_template_id, " - + "control_plane_request_id, request_hash, version_id, script_patch_version, " - + "runtime_flags_json, generation_config_revision, version_state_epoch, " - + "release_bundle_id, published_release_bundle_ref, remap_set_id, created_at " - + "FROM launch_descriptor WHERE tenant_id = ? AND control_plane_request_id = ?", - privateTenantKey, - controlPlaneRequestId); - if (record == null) { - throw new IllegalStateException("Retained V34 launch descriptor fixture is missing"); - } - return record.intoMap(); - } - - private Map retainedReleaseBundleSnapshot(DSLContext isolatedDsl, long bundleId) { - var record = - isolatedDsl.fetchOne( - "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " - + "publish_workflow_id, manifest_hash, generation_config_revision, " - + "required_manifest_asset_keys_json, participant_digests_json, " - + "command_definitions_json, script_only, script_patch_version, published_at " - + "FROM published_release_bundle WHERE id = ?", - bundleId); - if (record == null) { - throw new IllegalStateException("Retained V34 release bundle fixture is missing"); - } - return record.intoMap(); - } - - private String privateTenantKey() { - return "src-" + UUID.randomUUID().toString().replace("-", ""); - } - - private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { - assertThat(actual.getId()).isEqualTo(expected.getId()); - assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); - assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); - assertThat(actual.getGameTemplateId()).isEqualTo(expected.getGameTemplateId()); - assertThat(actual.getControlPlaneRequestId()).isEqualTo(expected.getControlPlaneRequestId()); - assertThat(actual.getRequestHash()).isEqualTo(expected.getRequestHash()); - assertThat(actual.getVersionId()).isEqualTo(expected.getVersionId()); - assertThat(actual.getScriptPatchVersion()).isEqualTo(expected.getScriptPatchVersion()); - assertThat(actual.getRuntimeFlagsJson()).isEqualTo(expected.getRuntimeFlagsJson()); - assertThat(actual.getGenerationConfigRevision()) - .isEqualTo(expected.getGenerationConfigRevision()); - assertThat(actual.getVersionStateEpoch()).isEqualTo(expected.getVersionStateEpoch()); - assertThat(actual.getReleaseBundleId()).isEqualTo(expected.getReleaseBundleId()); - assertThat(actual.getPublishedReleaseBundleRef()) - .isEqualTo(expected.getPublishedReleaseBundleRef()); - assertThat(actual.getRemapSetId()).isEqualTo(expected.getRemapSetId()); - assertThat(actual.getCreatedAt()).isEqualTo(expected.getCreatedAt()); - assertThat(actual.getDescriptorSchemaVersion()).isNull(); - assertThat(actual.getTargetNamespace()).isNull(); - assertThat(actual.getCanonicalTenantId()).isNull(); - assertThat(actual.getWorldSlug()).isNull(); - assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); - assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); - assertThat(actual.getRequestDigest()).isNull(); - assertThat(actual.getResultDigest()).isNull(); - assertThat(actual.getOriginalRequestJson()).isNull(); - assertThat(actual.getSourceEvidenceJson()).isNull(); - } - - private record Fixture( - String controlPlaneRequestId, - UUID canonicalTenantId, - String privateSourceTenantKey, - AuthoredWorldSourceEvidence source, - Version version, - GameTemplate template, - PublishedReleaseBundle bundle) { - AuthoredWorldLaunchDescriptorEvidence.Request request() { - return request(controlPlaneRequestId); - } - - AuthoredWorldLaunchDescriptorEvidence.Request request(String requestId) { - return new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - requestId, - canonicalTenantId, - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - template.getId(), - false, - null, - false, - null, - false, - null, - false, - null); - } - - AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { - return new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - controlPlaneRequestId, - canonicalTenantId, - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - template.getId(), - true, - patch, - false, - null, - false, - null, - false, - null); - } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index ce7ac958c7..0715b294f0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -9,13 +9,10 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -28,8 +25,6 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -79,7 +74,7 @@ public void onCompleted() {} } @Test - void launchReadsRequireExactSameNamespaceWorkloadIdentity() { + void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -98,54 +93,6 @@ void launchReadsRequireExactSameNamespaceWorkloadIdentity() { false, null, java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - AuthoredWorldLaunchDescriptorEvidence.Request launchRequest = - new AuthoredWorldLaunchDescriptorEvidence.Request( - "test", - "cp-1", - UUID.fromString("12345678-1234-4234-8234-123456789abc"), - "silver-march", - UUID.fromString("22345678-1234-4234-8234-123456789abc"), - "sha256:" + "a".repeat(64), - 9L, - false, - null, - false, - null, - false, - null, - false, - null); - AuthoredWorldLaunchDescriptorEvidence evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - launchRequest, - "ld-1", - 7L, - false, - null, - "{}", - "genrev-1", - 11L, - 11L, - "release-bundle:12345678-1234-4234-8234-123456789abc:7:11", - false, - null); - Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) - .thenReturn( - new ResolvedLaunchDescriptorDto( - evidence.launchDescriptorId(), - evidence.canonicalTenantId().toString(), - evidence.gameTemplateId(), - evidence.controlPlaneRequestId(), - evidence.versionId(), - evidence.scriptPatchVersion(), - evidence.runtimeFlagsJson(), - evidence.generationConfigRevision(), - evidence.versionStateEpoch(), - evidence.releaseBundleId(), - evidence.publishedReleaseBundleRef(), - evidence.remapSetId(), - evidence)); - GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -183,37 +130,10 @@ public void onError(Throwable t) {} public void onCompleted() {} })); - AtomicReference descriptorRef = new AtomicReference<>(); - underGameSessionPeer( - () -> - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .setWorldSlug("silver-march") - .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") - .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); - assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); - assertNotNull(descriptorRef.get()); - assertEquals("", descriptorRef.get().getError().getCode()); - assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); + Mockito.verifyNoInteractions(launchDescriptorService); } private void underGameSessionPeer(Runnable operation) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 47ce68a043..17bc613d39 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -2,7 +2,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -11,7 +10,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; @@ -20,7 +18,6 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; @@ -47,8 +44,6 @@ import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -1132,134 +1127,17 @@ void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { } @Test - void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-1"); - AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); - Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) - .thenReturn(launchDto(evidence)); - - AtomicReference ref = new AtomicReference<>(); - underLaunchPeer( - "game-session-service", - () -> service.resolveLaunchDescriptor(resolveRequest("cp-1"), observerFor(ref))); - - assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); - assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); - assertEquals( - evidence.resultDigest(), - ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); - Mockito.verify(launchDescriptorService).resolveLaunchDescriptor(request); - } - - @Test - void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) - .thenThrow( - new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); - - AtomicReference ref = new AtomicReference<>(); - underLaunchPeer( - "game-session-service", - () -> service.resolveLaunchDescriptor(resolveRequest("cp-2"), observerFor(ref))); - - assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); - } - - @Test - void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) - .thenThrow( - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - + void resolveLaunchDescriptorFailsClosedBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); - underLaunchPeer( - "game-session-service", - () -> service.resolveLaunchDescriptor(resolveRequest("cp-3"), observerFor(ref))); - - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); - } - - @Test - void getLaunchDescriptorReturnsExactBoundReadback() { - AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-read"); - AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); - Mockito.when( - launchDescriptorService.getLaunchDescriptor( - Mockito.eq(UUID.fromString("32345678-1234-4234-8234-123456789abc")), - Mockito.eq(CANONICAL_TENANT_ID), - Mockito.eq("silver-march"), - Mockito.eq("cp-read"), - Mockito.eq(evidence.requestDigest()), - Mockito.eq(evidence.resultDigest()))) - .thenReturn(launchDto(evidence)); - - AtomicReference ref = new AtomicReference<>(); - var readRequest = - GetLaunchDescriptorRequest.newBuilder() - .setRequestId("32345678-1234-4234-8234-123456789abc") - .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) - .setWorldSlug("silver-march") - .setControlPlaneRequestId("cp-read") - .setExpectedRequestDigest(evidence.requestDigest()) - .setExpectedResultDigest(evidence.resultDigest()) - .build(); - underLaunchPeer( - "world-management-service", () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); - - assertEquals("32345678-1234-4234-8234-123456789abc", ref.get().getRequestId()); - assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); - assertEquals( - evidence.resultDigest(), - ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); - Mockito.verify(launchDescriptorService) - .getLaunchDescriptor( - UUID.fromString("32345678-1234-4234-8234-123456789abc"), - CANONICAL_TENANT_ID, - "silver-march", - "cp-read", - evidence.requestDigest(), - evidence.resultDigest()); - } - - @Test - void resolveLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { - AtomicReference ref = new AtomicReference<>(); - var request = - resolveRequest("cp-unknown").toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build(); - underLaunchPeer( - "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(launchDescriptorService); - } - - @Test - void getLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { - AtomicReference ref = new AtomicReference<>(); - var request = - GetLaunchDescriptorRequest.newBuilder() - .setRequestId("32345678-1234-4234-8234-123456789abc") - .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) - .setWorldSlug("silver-march") - .setControlPlaneRequestId("cp-read") - .setExpectedRequestDigest("sha256:" + "a".repeat(64)) - .setExpectedResultDigest("sha256:" + "b".repeat(64)) - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build(); - underLaunchPeer( - "game-session-service", () -> service.getLaunchDescriptor(request, observerFor(ref))); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setTenantId("tenant-1") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-legacy") + .build(), + observerFor(ref)); + + assertEquals("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", ref.get().getError().getCode()); Mockito.verifyNoInteractions(launchDescriptorService); } @@ -1574,71 +1452,6 @@ private void underLaunchPeer(String serviceName, Runnable operation) { Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } - private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( - String controlPlaneRequestId) { - return new AuthoredWorldLaunchDescriptorEvidence.Request( - "test", - controlPlaneRequestId, - CANONICAL_TENANT_ID, - "silver-march", - UUID.fromString("22345678-1234-4234-8234-123456789abc"), - "sha256:" + "a".repeat(64), - 9L, - false, - null, - false, - null, - false, - null, - false, - null); - } - - private AuthoredWorldLaunchDescriptorEvidence launchEvidence( - AuthoredWorldLaunchDescriptorEvidence.Request request) { - return AuthoredWorldLaunchDescriptorEvidence.create( - request, - "ld-1", - 7L, - false, - null, - "{}", - "genrev-1", - 11L, - 11L, - "release-bundle:" + request.canonicalTenantId() + ":7:11", - false, - null); - } - - private ResolvedLaunchDescriptorDto launchDto(AuthoredWorldLaunchDescriptorEvidence evidence) { - return new ResolvedLaunchDescriptorDto( - evidence.launchDescriptorId(), - evidence.canonicalTenantId().toString(), - evidence.gameTemplateId(), - evidence.controlPlaneRequestId(), - evidence.versionId(), - evidence.scriptPatchVersion(), - evidence.runtimeFlagsJson(), - evidence.generationConfigRevision(), - evidence.versionStateEpoch(), - evidence.releaseBundleId(), - evidence.publishedReleaseBundleRef(), - evidence.remapSetId(), - evidence); - } - - private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { - return ResolveLaunchDescriptorRequest.newBuilder() - .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) - .setGameTemplateId(9L) - .setControlPlaneRequestId(controlPlaneRequestId) - .setWorldSlug("silver-march") - .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") - .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) - .build(); - } - private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 378f8aa1c8..16c2e8089f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -1,961 +1,54 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.clearInvocations; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; -import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; -import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; -import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; -import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.dao.DataAccessResourceFailureException; -import org.springframework.test.util.ReflectionTestUtils; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { - private static final String NAMESPACE = "test"; - private static final UUID CANONICAL_TENANT_ID = - UUID.fromString("12345678-1234-4234-8234-123456789abc"); - private static final UUID CANONICAL_VERSION_ID = - UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); - private static final UUID SOURCE_OPERATION_ID = - UUID.fromString("22345678-1234-4234-8234-123456789abc"); - private static final UUID SOURCE_REGISTRATION_ID = - UUID.fromString("32345678-1234-4234-8234-123456789abc"); - private static final String WORLD_SLUG = "silver-march"; - private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; - private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; - private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); - - @Mock private GameTemplateRepository gameTemplateRepository; - @Mock private LaunchDescriptorRepository launchDescriptorRepository; - @Mock private VersionRepository versionRepository; - @Mock private PublishedReleaseBundleService publishedReleaseBundleService; - @Mock private TemplateRemapSetService templateRemapSetService; - @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; - - private LaunchDescriptorServiceImpl service; - - @Test - void completeSelectorV2ResolvesTheUnchangedDescriptorV1Binding() throws Exception { - var request = request("cp-selector-v2", 9L); - stubSuccessfulLaunch(request, 7L, 11L); - var bundle = selectorBundle(false); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenReturn(bundle); - - var resolved = service.resolveLaunchDescriptor(request); - - assertEquals(7L, resolved.versionId()); - assertEquals(11L, resolved.releaseBundleId()); - assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); - assertEquals( - AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION, - resolved.authoredWorldBinding().schemaVersion()); - assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); - assertEquals(17L, resolved.versionStateEpoch()); - verify(launchDescriptorRepository).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSuccess() - throws Exception { - var request = request("cp-incomplete-selector-v2", 9L); - stubSuccessfulLaunch(request, 7L, 11L); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenReturn(selectorBundle(true)); - - assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); - } - - private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { - // Stipulated original component bytes; this fixture does not authenticate a producer or admit - // gameplay. - WorldPublishedStartLocationEvidence evidence = - PublishedWorldSelectorFixtures.evidence( - new TargetProof( - CANONICAL_TENANT_ID, - CANONICAL_VERSION_ID, - 7L, - PRIVATE_SOURCE_TENANT_KEY, - 1L, - PRIVATE_SOURCE_TENANT_KEY, - "NEW_GAME_ROW")); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); - return new PublishedReleaseBundleDto( - 11L, - PRIVATE_SOURCE_TENANT_KEY, - 7L, - 8, - "v2", - evidence.request().publishWorkflowId(), - MANIFEST_HASH, - List.of(), - omitParticipant ? participants.subList(0, 4) : participants, - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now(), - CANONICAL_TENANT_ID, - CANONICAL_VERSION_ID, - PUBLISHED_RELEASE_BUNDLE_REF, - 1, - List.of(), - evidence); - } - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - service = - new LaunchDescriptorServiceImpl( - gameTemplateRepository, - launchDescriptorRepository, - versionRepository, - publishedReleaseBundleService, - templateRemapSetService, - authoredWorldSourceRepository, - new ObjectMapper()); - ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); - } - - @Test - void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-1", 9L); - stubSuccessfulLaunch(request, 7L, 11L); - AtomicReference inserted = new AtomicReference<>(); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - inserted.set(descriptor); - return descriptor; - }); - - var resolved = service.resolveLaunchDescriptor(request); - - assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); - assertEquals(9L, resolved.gameTemplateId()); - assertEquals(7L, resolved.versionId()); - assertEquals("genrev-1", resolved.generationConfigRevision()); - assertEquals(17L, resolved.versionStateEpoch()); - assertEquals(11L, resolved.releaseBundleId()); - assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); - assertNotNull(resolved.authoredWorldBinding()); - assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); - assertEquals( - PRIVATE_SOURCE_TENANT_KEY, - inserted.get().getTenantId(), - "The private source key remains owner-local and is not the canonical tenant UUID"); - assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); - verify(authoredWorldSourceRepository) - .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); - verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); - verify(gameTemplateRepository, never()) - .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); - } - - @Test - void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOrRelease() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); - GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); - stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); - stubBundle(7L, 11L, "v1"); - AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); - stubSource(request, source); - AtomicReference stored = new AtomicReference<>(); - when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-retry")) - .thenAnswer(invocation -> Optional.ofNullable(stored.get())); - when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) - .thenReturn(Optional.empty()); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - stored.set(descriptor); - return descriptor; - }); - - var first = service.resolveLaunchDescriptor(request); - when(template.getDefaultVersionId()).thenReturn(8L); - when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - clearInvocations(template); - when(versionRepository.findById(8L)).thenReturn(Optional.empty()); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L)) - .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 8L)); - - var retry = service.resolveLaunchDescriptor(request); - - assertEquals(first, retry); - assertEquals(7L, retry.versionId()); - verify(gameTemplateRepository, times(1)) - .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); - verifyNoInteractions(template); - verify(versionRepository, times(1)).findById(7L); - verify(versionRepository, never()).findById(8L); - verify(publishedReleaseBundleService, times(1)) - .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); - verify(publishedReleaseBundleService, never()) - .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L); - verify(launchDescriptorRepository, times(1)).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void changedSourceScopeTemplateOrRequestCannotReplaceOriginalDescriptor() { - AuthoredWorldLaunchDescriptorEvidence.Request original = request("cp-conflict", 9L); - stubSuccessfulLaunch(original, 7L, 11L); - LaunchDescriptor stored = descriptorFor(original, 7L, 11L); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, "cp-conflict")) - .thenReturn(Optional.of(stored)); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - AuthoredWorldLaunchDescriptorEvidence.Request changedTemplate = request("cp-conflict", 10L); - IllegalArgumentException templateConflict = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedTemplate)); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", - templateConflict.getMessage()); - - AuthoredWorldLaunchDescriptorEvidence.Request changedRequest = - request("cp-conflict", 9L, true, "other-patch"); - IllegalArgumentException requestConflict = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedRequest)); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", - requestConflict.getMessage()); - - UUID otherOperation = UUID.fromString("42345678-1234-4234-8234-123456789abc"); - AuthoredWorldLaunchDescriptorEvidence.Request changedSource = - request("cp-conflict", 9L, otherOperation, WORLD_SLUG, CANONICAL_TENANT_ID); - when(authoredWorldSourceRepository.read( - otherOperation, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) - .thenReturn(Optional.empty()); - IllegalArgumentException sourceConflict = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedSource)); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", - sourceConflict.getMessage()); - - UUID otherCanonicalTenant = UUID.fromString("52345678-1234-4234-8234-123456789abc"); - AuthoredWorldLaunchDescriptorEvidence.Request changedTenantScope = - request("cp-conflict", 9L, SOURCE_OPERATION_ID, WORLD_SLUG, otherCanonicalTenant); - when(authoredWorldSourceRepository.read( - SOURCE_OPERATION_ID, otherCanonicalTenant, WORLD_SLUG, NAMESPACE)) - .thenReturn(Optional.empty()); - IllegalArgumentException scopeConflict = - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor(changedTenantScope)); - assertEquals( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", - scopeConflict.getMessage()); - - AuthoredWorldLaunchDescriptorEvidence.Request changedWorldScope = - request("cp-conflict", 9L, SOURCE_OPERATION_ID, "other-world", CANONICAL_TENANT_ID); - when(authoredWorldSourceRepository.read( - SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, "other-world", NAMESPACE)) - .thenReturn(Optional.empty()); - IllegalArgumentException worldConflict = - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor(changedWorldScope)); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", - worldConflict.getMessage()); - verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void exactReadbackReturnsOriginalEvidenceAndRejectsDigestOrScopeSubstitution() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-read", 9L); - stubSuccessfulLaunch(request, 7L, 11L); - LaunchDescriptor stored = descriptorFor(request, 7L, 11L); - when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-read")) - .thenReturn(Optional.of(stored)); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - var original = service.resolveLaunchDescriptor(request); - - var readback = - service.getLaunchDescriptor( - UUID.fromString("62345678-1234-4234-8234-123456789abc"), - CANONICAL_TENANT_ID, - WORLD_SLUG, - "cp-read", - original.authoredWorldBinding().requestDigest(), - original.authoredWorldBinding().resultDigest()); - - assertEquals(original, readback); - IllegalArgumentException changedRequestDigest = - assertThrows( - IllegalArgumentException.class, - () -> - service.getLaunchDescriptor( - UUID.fromString("72345678-1234-4234-8234-123456789abc"), - CANONICAL_TENANT_ID, - WORLD_SLUG, - "cp-read", - "sha256:" + "b".repeat(64), - original.authoredWorldBinding().resultDigest())); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", - changedRequestDigest.getMessage()); - - IllegalArgumentException changedResultDigest = - assertThrows( - IllegalArgumentException.class, - () -> - service.getLaunchDescriptor( - UUID.fromString("82345678-1234-4234-8234-123456789abc"), - CANONICAL_TENANT_ID, - WORLD_SLUG, - "cp-read", - original.authoredWorldBinding().requestDigest(), - "sha256:" + "c".repeat(64))); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", - changedResultDigest.getMessage()); - - IllegalArgumentException changedWorld = - assertThrows( - IllegalArgumentException.class, - () -> - service.getLaunchDescriptor( - UUID.fromString("92345678-1234-4234-8234-123456789abc"), - CANONICAL_TENANT_ID, - "other-world", - "cp-read", - original.authoredWorldBinding().requestDigest(), - original.authoredWorldBinding().resultDigest())); - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", - changedWorld.getMessage()); - verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-patch", 9L); - GameTemplateLaunchConfigView template = stubTemplate(request, 7L, "patch-1"); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", - thrown.getMessage()); - verify(template).getDefaultScriptPatchVersion(); - org.mockito.ArgumentCaptor failure = - org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); - verify(launchDescriptorRepository).insertImmutable(failure.capture()); - assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); - assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); - assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); - assertEquals(null, failure.getValue().getLaunchDescriptorId()); - assertEquals(null, failure.getValue().getVersionId()); - } - - @Test - void sourceAndTransientDependencyFailuresDoNotCreateFrozenOutcomes() { - AuthoredWorldLaunchDescriptorEvidence.Request missingSource = request("cp-no-source", 9L); - when(authoredWorldSourceRepository.read( - SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) - .thenReturn(Optional.empty()); - - IllegalArgumentException sourceFailure = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(missingSource)); - assertEquals( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", - sourceFailure.getMessage()); - - AuthoredWorldLaunchDescriptorEvidence.Request changedSourceEvidence = - new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - "cp-changed-source", - CANONICAL_TENANT_ID, - WORLD_SLUG, - SOURCE_OPERATION_ID, - "sha256:" + "f".repeat(64), - 9L, - false, - null, - false, - null, - false, - null, - false, - null); - stubSource(changedSourceEvidence, sourceEvidence(WORLD_SLUG)); - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor(changedSourceEvidence)); - - AuthoredWorldLaunchDescriptorEvidence.Request unavailableDependency = - request("cp-unavailable", 9L); - stubSource(unavailableDependency, sourceEvidence(WORLD_SLUG)); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L)) - .thenThrow(new DataAccessResourceFailureException("temporary database outage")); - - assertThrows( - DataAccessResourceFailureException.class, - () -> service.resolveLaunchDescriptor(unavailableDependency)); - verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-frozen-failure", 9L); - AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); - LaunchDescriptor failure = new LaunchDescriptor(); - failure.setTenantId(PRIVATE_SOURCE_TENANT_KEY); - failure.setControlPlaneRequestId(request.controlPlaneRequestId()); - failure.setRequestHash(request.requestDigest()); - failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); - failure.setTargetNamespace(NAMESPACE); - failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); - failure.setWorldSlug(WORLD_SLUG); - failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); - failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); - failure.setRequestDigest(request.requestDigest()); - failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); - failure.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); - failure.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); - failure.setFailureCode("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); - failure.setFailureMessage("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial"); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) - .thenReturn(Optional.of(failure)); - stubSource(request, source); - - FrozenLaunchDescriptorDenialException thrown = - assertThrows( - FrozenLaunchDescriptorDenialException.class, - () -> service.resolveLaunchDescriptor(request)); - - assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", thrown.failureCode()); - assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial", thrown.getMessage()); - verify(gameTemplateRepository, never()) - .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); - verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); - } - - @Test - void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered", 9L); - stubSuccessfulLaunch(request, 7L, 11L); - LaunchDescriptor stored = descriptorFor(request, 7L, 11L); - stored.setScriptPatchVersion("patch-1"); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, "cp-tampered")) - .thenReturn(Optional.of(stored)); - + private final GameTemplateRepository gameTemplateRepository = mock(GameTemplateRepository.class); + private final LaunchDescriptorRepository launchDescriptorRepository = + mock(LaunchDescriptorRepository.class); + private final VersionRepository versionRepository = mock(VersionRepository.class); + private final PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + private final TemplateRemapSetService templateRemapSetService = + mock(TemplateRemapSetService.class); + private final ObjectMapper objectMapper = mock(ObjectMapper.class); + private final LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + objectMapper); + + @Test + void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent", - thrown.getMessage()); - } - - @Test - void resolveLaunchDescriptorPreservesTemplatePhaseGate() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); - GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.LEGACY); - stubSource(request, sourceEvidence(WORLD_SLUG)); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced", - thrown.getMessage()); - } - - @Test - void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-schema", 9L); - stubTemplate(request, 7L, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenReturn(releaseBundle(7L, 11L, "v999")); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - true, - thrown - .getMessage() - .startsWith( - "SCHEMA_VERSION_UNSUPPORTED: unsupported published release bundle attestation schema")); - } - - @Test - void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-release", 9L); - stubTemplate(request, 7L, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 7L)); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", - thrown.getMessage()); - } - - @Test - void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-reference", 9L); - stubTemplate(request, 7L, null); - AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); - stubSource(request, source); - stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenReturn(releaseBundle(7L, 11L, "v1", null)); - AtomicReference stored = new AtomicReference<>(); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) - .thenAnswer(invocation -> Optional.ofNullable(stored.get())); - when(launchDescriptorRepository.findByPrivateRequest( - PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) - .thenReturn(Optional.empty()); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - stored.set(descriptor); - return descriptor; - }); - - IllegalArgumentException first = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - IllegalArgumentException retry = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "RELEASE_BUNDLE_NOT_FOUND: published release bundle has no persisted opaque reference", - first.getMessage()); - assertEquals(first.getMessage(), retry.getMessage()); - assertEquals(LaunchDescriptor.OUTCOME_FAILED, stored.get().getOutcomeStatus()); - assertEquals("RELEASE_BUNDLE_NOT_FOUND", stored.get().getFailureCode()); - assertNull(stored.get().getPublishedReleaseBundleRef()); - verify(publishedReleaseBundleService, times(1)) - .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); - } - - @Test - void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); - Long resolvedVersionId = boxedLargeVersionId(); - Long bundleVersionId = boxedLargeVersionId(); - assertNotSame(resolvedVersionId, bundleVersionId); - stubTemplate(request, resolvedVersionId, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) - .thenReturn(releaseBundle(bundleVersionId, 11L, "v1")); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) - .thenReturn(Optional.empty()); - when(launchDescriptorRepository.findByPrivateRequest( - PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) - .thenReturn(Optional.empty()); - - var resolved = service.resolveLaunchDescriptor(request); - - assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); - assertEquals(9L, resolved.gameTemplateId()); - assertEquals(1_000L, resolved.versionId()); - assertEquals(11L, resolved.releaseBundleId()); - assertNotNull(resolved.authoredWorldBinding()); - assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); - assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); - } - - @Test - void resolveLaunchDescriptorRejectsReleaseBundleForDifferentVersionDeterministically() { - AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-mismatched-release", 9L); - stubTemplate(request, 1_000L, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); - when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) - .thenReturn(releaseBundle(1_001L, 11L, "v1")); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); - - assertEquals( - "RELEASE_BUNDLE_NOT_FOUND: release bundle is not owned by the resolved source version", - thrown.getMessage()); - } - - @Test - void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { - AuthoredWorldLaunchDescriptorEvidence.Request request = - request("cp-remap-required", 9L, 7L, 8L); - stubTemplate(request, 8L, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); - when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) - .thenReturn(Optional.empty()); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor("1", 9L, "cp-1", null, null, null, null)); assertEquals( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor", thrown.getMessage()); - } - - @Test - void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { - AuthoredWorldLaunchDescriptorEvidence.Request request = - request("cp-remap-approved", 9L, 7L, 8L); - stubTemplate(request, 8L, null); - stubSource(request, sourceEvidence(WORLD_SLUG)); - stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); - when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) - .thenReturn( - Optional.of( - new TemplateRemapSetDto( - "remap-1", - PRIVATE_SOURCE_TENANT_KEY, - 7L, - 8L, - TemplateRemapSetStatus.APPROVED, - "preparation", - "approved", - LocalDateTime.now(), - LocalDateTime.now(), - List.of()))); - stubBundle(8L, 11L, "v1"); - when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - var resolved = service.resolveLaunchDescriptor(request); - - assertEquals("remap-1", resolved.remapSetId()); - assertEquals("remap-1", resolved.authoredWorldBinding().remapSetId()); - } - - private void stubSuccessfulLaunch( - AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { - stubTemplate(request, versionId, null); - stubSource(request, sourceEvidence(request.worldSlug())); - stubVersion(versionId, VersionLifecycleState.PUBLISHED, 17L, null); - stubBundle(versionId, bundleId, "v1"); - when(launchDescriptorRepository.findBoundByRequest( - NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) - .thenReturn(Optional.empty()); - when(launchDescriptorRepository.findByPrivateRequest( - PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) - .thenReturn(Optional.empty()); - } - - private GameTemplateLaunchConfigView stubTemplate( - AuthoredWorldLaunchDescriptorEvidence.Request request, - Long defaultVersionId, - String defaultPatch) { - GameTemplateLaunchConfigView template = Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(request.gameTemplateId()); - when(template.getTenantId()).thenReturn(PRIVATE_SOURCE_TENANT_KEY); - when(template.getDefaultVersionId()).thenReturn(defaultVersionId); - when(template.getDefaultScriptPatchVersion()).thenReturn(defaultPatch); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId( - PRIVATE_SOURCE_TENANT_KEY, request.gameTemplateId())) - .thenReturn(Optional.of(template)); - return template; - } - - private void stubSource( - AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { - when(authoredWorldSourceRepository.read( - request.authoredWorldSourceOperationId(), - request.canonicalTenantId(), - request.worldSlug(), - NAMESPACE)) - .thenReturn(Optional.of(source)); - } - - private void stubVersion( - long versionId, VersionLifecycleState state, long epoch, String scriptPatchVersion) { - Version version = new Version(); - version.setId(versionId); - version.setTenantId(PRIVATE_SOURCE_TENANT_KEY); - version.setVersionNumber(8); - version.setVersionState(state); - version.setVersionStateEpoch(epoch); - version.setScriptPatchVersion(scriptPatchVersion); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(versionId)).thenReturn(Optional.of(version)); - } - - private void stubBundle(long versionId, long bundleId, String schemaVersion) { - when(publishedReleaseBundleService.getPublishedReleaseBundle( - PRIVATE_SOURCE_TENANT_KEY, versionId)) - .thenReturn(releaseBundle(versionId, bundleId, schemaVersion)); - } - - private PublishedReleaseBundleDto releaseBundle( - Long versionId, long bundleId, String schemaVersion) { - return releaseBundle(versionId, bundleId, schemaVersion, PUBLISHED_RELEASE_BUNDLE_REF); - } - - private PublishedReleaseBundleDto releaseBundle( - Long versionId, long bundleId, String schemaVersion, String publishedReleaseBundleRef) { - return new PublishedReleaseBundleDto( - bundleId, - PRIVATE_SOURCE_TENANT_KEY, - versionId, - 8, - schemaVersion, - "workflow-1", - MANIFEST_HASH, - List.of(), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now(), - CANONICAL_TENANT_ID, - CANONICAL_VERSION_ID, - publishedReleaseBundleRef, - 1, - List.of()); - } - - @SuppressWarnings("removal") - private Long boxedLargeVersionId() { - return new Long(1_000L); - } - - private LaunchDescriptor descriptorFor( - AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { - var evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - request, - "ld-stored-" + request.controlPlaneRequestId(), - versionId, - false, - null, - "{}", - "genrev-1", - 17L, - bundleId, - PUBLISHED_RELEASE_BUNDLE_REF, - false, - null); - AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); - LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); - descriptor.setTenantId(PRIVATE_SOURCE_TENANT_KEY); - descriptor.setGameTemplateId(request.gameTemplateId()); - descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); - descriptor.setRequestHash(evidence.requestDigest()); - descriptor.setVersionId(evidence.versionId()); - descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); - descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); - descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); - descriptor.setReleaseBundleId(evidence.releaseBundleId()); - descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); - descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); - descriptor.setTargetNamespace(evidence.targetNamespace()); - descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); - descriptor.setWorldSlug(evidence.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - evidence.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); - descriptor.setRequestDigest(evidence.requestDigest()); - descriptor.setResultDigest(evidence.resultDigest()); - descriptor.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); - descriptor.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); - return descriptor; - } - - private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { - String tenantSlug = "silver-company"; - String displayName = "Silver March 🐉"; - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - NAMESPACE, - SOURCE_REGISTRATION_ID, - CANONICAL_TENANT_ID, - tenantSlug, - worldSlug, - displayName); - return new AuthoredWorldSourceEvidence( - 1, - NAMESPACE, - SOURCE_REGISTRATION_ID, - SOURCE_OPERATION_ID, - requestDigest, - CANONICAL_TENANT_ID, - tenantSlug, - worldSlug, - displayName, - 901L, - PRIVATE_SOURCE_TENANT_KEY, - "NEW_GAME_ROW", - AuthoredWorldSourceDigest.evidenceDigest( - NAMESPACE, - SOURCE_REGISTRATION_ID, - SOURCE_OPERATION_ID, - requestDigest, - CANONICAL_TENANT_ID, - tenantSlug, - worldSlug, - displayName, - 901L, - PRIVATE_SOURCE_TENANT_KEY, - "NEW_GAME_ROW")); - } - - private AuthoredWorldLaunchDescriptorEvidence.Request request( - String controlPlaneRequestId, long gameTemplateId) { - return request( - controlPlaneRequestId, - gameTemplateId, - SOURCE_OPERATION_ID, - WORLD_SLUG, - CANONICAL_TENANT_ID); - } - - private AuthoredWorldLaunchDescriptorEvidence.Request request( - String controlPlaneRequestId, - long gameTemplateId, - long sourceVersionId, - long targetVersionId) { - return new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - controlPlaneRequestId, - CANONICAL_TENANT_ID, - WORLD_SLUG, - SOURCE_OPERATION_ID, - sourceEvidence(WORLD_SLUG).evidenceDigest(), - gameTemplateId, - false, - null, - true, - sourceVersionId, - true, - targetVersionId, - false, - null); - } - - private AuthoredWorldLaunchDescriptorEvidence.Request request( - String controlPlaneRequestId, - long gameTemplateId, - boolean requestedPatchPresent, - String requestedPatch) { - return new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - controlPlaneRequestId, - CANONICAL_TENANT_ID, - WORLD_SLUG, - SOURCE_OPERATION_ID, - sourceEvidence(WORLD_SLUG).evidenceDigest(), - gameTemplateId, - requestedPatchPresent, - requestedPatch, - false, - null, - false, - null, - false, - null); - } - - private AuthoredWorldLaunchDescriptorEvidence.Request request( - String controlPlaneRequestId, - long gameTemplateId, - UUID operationId, - String worldSlug, - UUID canonicalTenantId) { - String evidenceDigest = - SOURCE_OPERATION_ID.equals(operationId) - && WORLD_SLUG.equals(worldSlug) - && CANONICAL_TENANT_ID.equals(canonicalTenantId) - ? sourceEvidence(WORLD_SLUG).evidenceDigest() - : "sha256:" + "a".repeat(64); - return new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - controlPlaneRequestId, - canonicalTenantId, - worldSlug, - operationId, - evidenceDigest, - gameTemplateId, - false, - null, - false, - null, - false, - null, - false, - null); + verifyNoInteractions( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + objectMapper); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index acf2340aa7..b090816e15 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -1220,9 +1220,69 @@ private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { } private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" - + " required"); + if (gameDesignClient == null) { + throw new IllegalStateException("launch descriptor authority unavailable"); + } + var descriptorResponse = + gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + if (descriptorResponse.hasError()) { + throw new IllegalArgumentException( + descriptorResponse.getError().getCode() + + ": " + + descriptorResponse.getError().getMessage()); + } + var descriptor = descriptorResponse.getLaunchDescriptor(); + var bundleResponse = + gameDesignClient.getPublishedReleaseBundle(request.tenantId(), descriptor.getVersionId()); + if (bundleResponse.hasError()) { + throw new IllegalArgumentException( + bundleResponse.getError().getCode() + ": " + bundleResponse.getError().getMessage()); + } + var bundle = bundleResponse.getBundle(); + requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); + if (bundle.getId() != descriptor.getReleaseBundleId() + || bundle.getVersionId() != descriptor.getVersionId() + || !bundle.getGenerationConfigRevision().equals(descriptor.getGenerationConfigRevision()) + || !releaseBundleRef(request.tenantId(), descriptor.getVersionId(), bundle.getId()) + .equals(descriptor.getPublishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "RELEASE_ATTESTATION_MISMATCH: resolved launch descriptor does not match the published" + + " release bundle"); + } + validatePublishedAssetProof(request.tenantId(), descriptor.getVersionId(), bundle); + var versionStateResponse = + gameDesignClient.getVersionState(request.tenantId(), descriptor.getVersionId()); + if (versionStateResponse.hasError()) { + throw new IllegalArgumentException( + versionStateResponse.getError().getCode() + + ": " + + versionStateResponse.getError().getMessage()); + } + var versionState = versionStateResponse.getVersionState(); + if (versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); + } + if (versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch()) { + throw new IllegalArgumentException( + "VERSION_STATE_EPOCH_STALE: resolved launch descriptor epoch does not match current" + + " version state"); + } + return new ResolvedLaunchDescriptor( + descriptor.getLaunchDescriptorId(), + requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), + descriptor.getGameTemplateId(), + descriptor.getControlPlaneRequestId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); } private void validatePublishedAssetProof( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 9161200d9e..e7bf134b4a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -133,6 +133,18 @@ void startSessionSavesState() { @Test void legacyNumericLaunchFailsClosedBeforeMutation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-numeric-launch", 42L); + when( + gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId())) + .thenReturn( + ResolveLaunchDescriptorResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build()); assertNumericLaunchDeniedWithoutMutation(request); } @@ -1483,11 +1495,15 @@ private void assertNumericLaunchDeniedWithoutMutation(StartSessionRequest reques assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); assertEquals( - "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" - + " required", + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: Canonical authored-world source binding is" + + " required to resolve a launch descriptor", error.getMessage()); org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); - verifyNoInteractions(repository, gameDesignClient, worldManagementClient, stateService); + verify(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + verifyNoMoreInteractions(gameDesignClient); + verifyNoInteractions(repository, worldManagementClient, stateService); } @Test From cba57c4b9d4e13a5b2f1de7c69bad9f14e86b1a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:09:18 +1300 Subject: [PATCH 04/29] Complete durable asset staging and source-foundation caller proof --- .../config/AssetStoreProperties.java | 1 + .../VersionPublishCommandServiceImpl.java | 26 ++- ...emptServiceTransactionIntegrationTest.java | 26 ++- ...olicyPublicationReadConfigurationTest.java | 3 - .../TenantIdentityGrpcAuthWiringTest.java | 9 +- .../impl/GameDesignGrpcServiceAuthTest.java | 27 ++- .../impl/GameDesignGrpcServiceTest.java | 19 +- .../VersionPublishCommandServiceImplTest.java | 206 +++++++++++++++--- .../service/impl/VersionServiceImplTest.java | 23 +- .../client/GameDesignClientTest.java | 3 +- .../impl/GameInstanceServiceImplTest.java | 5 +- 11 files changed, 288 insertions(+), 60 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java index dadeac19cc..fa193d575c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java @@ -12,6 +12,7 @@ public class AssetStoreProperties { private static final int DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES = 256; private String endpoint; + private String publicBaseUrl; private String bucket; private String region; private String accessKey; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index f5dcf8a99e..d8c304601e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -21,8 +21,8 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; +import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; @@ -167,6 +167,30 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } + VersionAssetArtifactStateDto stagedArtifact; + try { + stagedArtifact = + versionAssetArtifactService.stageExport( + request.tenantId(), + version.getId(), + dto.versionNumber(), + request.publishWorkflowId()); + } catch (RuntimeException ex) { + throw pendingReconciliation( + "asset export staging outcome is pending; retry exact publish request", ex); + } + if (stagedArtifact == null + || !Objects.equals(stagedArtifact.tenantId(), request.tenantId()) + || !Objects.equals(stagedArtifact.versionId(), version.getId()) + || stagedArtifact.exportedVersionNumber() != dto.versionNumber() + || !Objects.equals(stagedArtifact.lastWorkflowId(), request.publishWorkflowId()) + || stagedArtifact.stateEpoch() <= 0 + || !("STAGED".equals(stagedArtifact.artifactState()) + || "EXPORTED_UNATTESTED".equals(stagedArtifact.artifactState()))) { + throw pendingReconciliation( + "asset export staging did not confirm the exact pending publish scope; " + + "retry the exact publish request"); + } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 532f2479f9..16eca38f83 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -67,6 +67,8 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); @Container static PostgreSQLContainer postgres = @@ -247,9 +249,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth null, null)); }); - Mockito.when(assetExportService.exportAssets(tenantId, 1)) - .thenReturn( - new ExportedAssetManifest("transaction-proof-manifest", List.of("manifest.json"))); + Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(exportedManifest()); VersionDto publishedVersion = versionPublishCommandService.publishFullVersion( @@ -272,7 +272,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); - assertThat(bundle.getManifestHash()).isEqualTo("transaction-proof-manifest"); + assertThat(bundle.getManifestHash()).isEqualTo(MANIFEST_HASH); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } @@ -341,8 +341,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .when(recordedParticipantDigestService) .assertMatchesRecordedDigests( Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("post-export-finalization-manifest", List.of("manifest.json")); + ExportedAssetManifest exportedManifest = exportedManifest(); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) .thenAnswer( invocation -> { @@ -448,4 +447,19 @@ private static String firstStackFrame(Throwable failure) { } return failure.getStackTrace()[0].toString(); } + + private static ExportedAssetManifest exportedManifest() { + return new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("manifest.json"), + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "application/json", + 1))); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index 1ed06c63b4..a68ad48040 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -87,9 +87,6 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) .orElse(List.of())) .containsExactly( - "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", - "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation", - "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource", "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies")); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index bb5a58ce07..c0507bdcc0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -51,6 +51,11 @@ class TenantIdentityGrpcAuthWiringTest { private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final List CONFIGURED_PUBLIC_METHODS = + List.of( + FRESH_CREATION_METHOD, + "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", + "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies"); private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; @@ -65,7 +70,7 @@ class TenantIdentityGrpcAuthWiringTest { void defaultAndProductionProfilesAllowOnlyFreshReadAndRequireClientTls() throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); - assertThat(config.publicMethods()).containsExactly(FRESH_CREATION_METHOD); + assertThat(config.publicMethods()).containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -180,7 +185,7 @@ private static void withConfiguredInterceptor(Consumer act context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(FRESH_CREATION_METHOD); + .containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 0715b294f0..311da15abf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; 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; @@ -16,6 +17,7 @@ import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -31,6 +33,12 @@ import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + @AfterEach void tearDown() { SessionContext.clear(); @@ -86,13 +94,25 @@ void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { 8, "v1", "workflow-1", - "hash-1", + MANIFEST_HASH, List.of("manifest.json"), List.of(), "genrev-1", false, null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); + java.time.LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -138,8 +158,7 @@ public void onCompleted() {} private void underGameSessionPeer(Runnable operation) { GrpcPeerIdentity peer = - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") - .orElseThrow(); + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 17bc613d39..ffba052595 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -225,8 +225,7 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { ref.get().getBundle().getPublishedReleaseBundleRef()); assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); assertEquals( - "82345678-1234-4234-8234-123456789abc", - ref.get().getBundle().getCanonicalVersionId()); + "82345678-1234-4234-8234-123456789abc", ref.get().getBundle().getCanonicalVersionId()); assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); @@ -1064,13 +1063,25 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { 8, "v999", "workflow-1", - "abc123", + "sha256:" + "a".repeat(64), List.of("manifest.json"), List.of(), "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 0cfc1f29a5..c69756353f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -14,6 +14,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -31,13 +32,14 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; +import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; @@ -51,6 +53,12 @@ import org.mockito.MockitoAnnotations; class VersionPublishCommandServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @Mock private PublishAttemptRepository publishAttemptRepository; @@ -72,6 +80,22 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(versionAssetArtifactService.stageExport( + any(String.class), any(Long.class), any(Integer.class), any(String.class))) + .thenAnswer( + invocation -> + new VersionAssetArtifactStateDto( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + "STAGED", + 1L, + null, + invocation.getArgument(3), + null, + null, + LocalDateTime.now(), + List.of())); org.mockito.Mockito.doAnswer( invocation -> { try { @@ -149,8 +173,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { Optional.of(savedDraft), Optional.of(savedPublished)); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")); + ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); List participantDigests = List.of( @@ -174,7 +197,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -187,14 +210,14 @@ void publishFullVersionUsesTenantScopedVersionSequence() { any(String.class), any(List.class))) .thenReturn( - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 8, "v1", "publish:tenant-1:publish-request:workflow-1", - "abc123", + MANIFEST_HASH, List.of("logo.png", "manifest.json"), participantDigests, "genrev-tenant-1-10", @@ -214,7 +237,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "PUBLISHED", 2L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -234,10 +257,22 @@ void publishFullVersionUsesTenantScopedVersionSequence() { verify(recordedParticipantDigestService) .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - InOrder publishOrder = inOrder(publishGateService, publishAttemptService, assetExportService); + InOrder publishOrder = + inOrder( + publishGateService, + recordedParticipantDigestService, + versionAssetArtifactService, + assetExportService, + publishAttemptService); publishOrder .verify(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); + publishOrder + .verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); + publishOrder + .verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 8, "publish:tenant-1:publish-request:workflow-1"); publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); publishOrder .verify(publishAttemptService) @@ -399,7 +434,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(new ExportedAssetManifest("abc123", List.of("manifest.json"))); + .thenReturn(exportedManifest(List.of("manifest.json"))); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn( @@ -421,7 +456,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { 1, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -461,14 +496,14 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { null, null)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), driftedParticipantDigests, "generation-revision", @@ -534,14 +569,14 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 11L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -624,14 +659,14 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -727,6 +762,62 @@ void uncertainAssetExportRemainsPendingForExactRetry() { .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } + @Test + void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenThrow(new IllegalStateException("stage commit outcome is unknown")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(versionAssetArtifactService).stageExport("tenant-1", 10L, 1, workflowId); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + verify(versionAssetArtifactService, never()) + .markFailed( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + @Test void readbackWithArtifactButNoBundleRemainsPartial() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -739,7 +830,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -774,14 +865,14 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); List participantDigests = participantDigests(); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -795,7 +886,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { 1, "PUBLISHED", 2L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -989,17 +1080,16 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); List participantDigests = participantDigests(); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -1028,7 +1118,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -1070,8 +1160,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); @@ -1144,8 +1233,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -1179,8 +1267,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1223,8 +1310,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); @@ -1296,4 +1382,58 @@ private List participantDigests() { new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest", 1, null, null)); } + + private static ExportedAssetManifest exportedManifest(List usageKeys) { + return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); + } + + private static List artifactDigests(List usageKeys) { + return usageKeys.stream() + .map( + usageKey -> + new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "manifest.json".equals(usageKey) ? "application/json" : "image/png", + 1)) + .toList(); + } + + private static PublishedReleaseBundleDto publishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + List.of(), + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(requiredManifestAssetKeys)); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 0b5e69a1b9..34bb6b3cbe 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -16,6 +16,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -49,6 +50,7 @@ import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; @@ -65,6 +67,11 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @@ -1523,7 +1530,7 @@ private PublishedReleaseBundleDto publishedReleaseBundle( 7, "v1", "workflow-1", - "manifest-1", + MANIFEST_HASH, List.of("manifest.json"), List.of( new PublishParticipantDigestDto( @@ -1537,7 +1544,19 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "genrev-1", false, null, - LocalDateTime.parse("2026-04-26T10:00:00")); + LocalDateTime.parse("2026-04-26T10:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1))); } private PublishedPluginVersion uploadedPluginVersion( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index 8c9a4d9d96..9a69375ede 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -76,8 +76,7 @@ private static GameDesignClient newClient( } private static GameDesignClient newClient( - GameDesignServiceGrpc.GameDesignServiceBlockingStub stub, - GrpcChannelFactory channelFactory) + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub, GrpcChannelFactory channelFactory) throws Exception { GameDesignClient client = new GameDesignClient( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index e7bf134b4a..6b3aab6ed1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -133,9 +133,8 @@ void startSessionSavesState() { @Test void legacyNumericLaunchFailsClosedBeforeMutation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-numeric-launch", 42L); - when( - gameDesignClient.resolveLaunchDescriptor( - request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId())) + when(gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId())) .thenReturn( ResolveLaunchDescriptorResponse.newBuilder() .setError( From 2bd316482e5c7107616bdd322d54108692d661d9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:47:53 +1300 Subject: [PATCH 05/29] Gate selected publication on genuine owners and preserve conditional mechanics proof --- .../game-design-service/api-contracts.md | 8 +- ...ame-authoring-publishing-and-activation.md | 12 +- .../game-design/v1/game_design_service.proto | 7 + .../gamedesign/service/VersionService.java | 8 +- .../service/impl/GameDesignGrpcService.java | 50 +- .../service/impl/PublishWorkflowRequest.java | 21 +- .../PublishedReleaseBundleServiceImpl.java | 39 +- .../VersionPublishCommandServiceImpl.java | 519 ++++-- .../service/impl/VersionServiceImpl.java | 31 +- .../impl/GameDesignGrpcServiceTest.java | 138 +- ...PublishedReleaseBundleServiceImplTest.java | 288 ++-- ...poralVersionPublishActivitiesImplTest.java | 188 +++ .../VersionPublishCommandServiceImplTest.java | 1385 ++++++++++------- .../service/impl/VersionServiceImplTest.java | 144 +- 14 files changed, 1815 insertions(+), 1023 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 2d43e4a5bd..2e17837226 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -49,7 +49,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V30 exact creation-operation persistence, the owner-local transaction producer and source readback, and the exact Account/Game Session peer receipt read RPC. Validation evidence and remaining gaps belong to the linked implementation tracker. No creator RPC or authenticated creator authority is wired, and no Account association, membership, JOIN, or runtime admission is enabled by this source. -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The full-version proto carries the exact selected existing Version, expected state epoch, and synchronized commit request/commit/digest; a selected request currently fails closed before reservation because the public service has no current Account authorization and authenticated owner-freeze producer. The old request shape is accepted only for exact retained terminal replay: it cannot create a new attempt or promote a pending one. The lower-level Temporal/command implementations remain in source, but new publication is not started by the public caller. The four owner-to-owner digest read handlers use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; this does not establish end-to-end publication authority. Full-version publication remains blocked because Game Logic owner manifest and provenance for rule inputs are absent, Automation's content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). The selected finalizer requires a captured publication operation and same-transaction terminal seal; the legacy five-argument release-bundle entrypoint now rejects, so mutable revision rows cannot synthesize a new version-1 bundle. These guarded mechanisms are not evidence of a reachable success path. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. The following implementation and proof gaps remain in these live paths: @@ -78,7 +78,7 @@ For retries, World Management's ledger lookup makes the same mutation identity ( The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. -When Temporal is disabled or its beans are absent, `PublishVersion` uses the same deterministic publish-attempt and reconciliation gates synchronously, including release-bundle and release-attestation commitment. It returns terminal success only for a committed, fully finalized publish. After a downstream exception, exact readback either reconciles complete release evidence, leaves partial evidence pending, or proves that no release bundle or artifact exists while the candidate Version remains `DRAFT`; in the last case, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row. Best-effort object-store cleanup can still be uncertain after that failure is committed. The current fallback has no Temporal restart durability, workflow run ID, or independent workflow status metadata (`GetPublishedReleaseBundle` reports the disabled/unavailable runtime condition), and it must not be described as providing the target Temporal terminality guarantee. Once the Temporal authorization and worker/readback proofs are live, that target path conditionally supplies restart-independent workflow durability and terminal workflow status; the current implementation does not. +When Temporal is disabled or its beans are absent, the public `PublishVersion` path still fails closed for selected new requests; it does not run a synchronous publication fallback. The old request shape reaches only the command's retained terminal replay logic, which returns the exact already-succeeded version or original failure after checking retained attempt/bundle evidence; absent and pending attempts are rejected because they lack selected immutable source. The command's captured-operation finalizer and release-bundle path are not reachable through a successful public request until the missing authorization and owner-freeze producer is supplied. No Temporal restart durability, workflow run ID, or independent workflow status metadata is established by legacy terminal replay. The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). @@ -90,7 +90,7 @@ The published realm-policy owner read is present behind the default-off `firemud - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. - `ResolvePublishedRealmEntryPolicy` – returns immutable Game Design policy and provenance for one exact canonical tenant/version and world/realm selector pair; it does not compose runtime catalog or admission state. - `ListPublishedRealmEntryPolicies` – returns the complete bounded policy set and owner-bound count/digest for one exact canonical tenant/version; it does not activate runtime state. -- `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. +- `PublishVersion` – accepts the exact selected existing Version, expected state epoch, and synchronized commit request/commit/digest identity before attempting publication. Current new-publication authorization is fail-closed until Account authorization and authenticated owner-freeze production are wired; the no-selection legacy shape is limited to retained terminal replay. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. @@ -166,7 +166,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes a frozen version. Callers must provide a stable `publish_request_id`. Target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. When Temporal is absent or disabled, the service synchronously runs the local publish command using the same derived ID as its local publish-attempt idempotency key; this is not a Temporal workflow and provides no workflow-runtime recovery metadata. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed, but the current Temporal path is still not proved end to end because content-scope and live mounted-certificate/activity evidence remain incomplete; neither path may be described as stronger than its stated evidence. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes the exact selected frozen version. A new request carries stable `publish_request_id`, canonical selected `version_id`, `expected_version_state_epoch`, `selected_commit_request_id`, `selected_commit_id`, and `selected_commit_digest`; the complete synchronized commit is captured before source material is frozen. Target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from the request ID and returns success only after terminal workflow success and committed release attestation. Timeout or failure remains explicit and may be outcome-pending until durable readback resolves it; no half-complete success is exposed. Retrying the same request must preserve its original selection and captured source bytes. The current public selected path remains fail-closed until genuine Account authorization and authenticated owner-freeze production exist; the legacy no-selection request shape is limited to exact retained terminal replay and cannot authorize a new or pending publication. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index f373c4f018..f4a18a3a7f 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -24,9 +24,9 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. -AR-1.5 full-version publication now reserves its Draft version and PENDING attempt together, keeps participant collection/export outside the final local transaction, and finalizes release bundle, Published version/artifact, verified baseline, and SUCCEEDED attempt atomically. A definite failure retains the candidate version and, only after exact readback confirms no release evidence, marks the attempt FAILED and any exported artifact FAILED; partial or committed release evidence remains PENDING for reconciliation. Same-request retries can still race during external participant/export work before the final game-row lock; no durable external-phase owner, private candidate namespace, or object-export deduplication was added in this bounded slice. Because export writes mutable tenant/version object keys, a late retry may overwrite bytes after another request has committed their release attestation; a failing retry can also mark the shared attempt failed or clean up keys while another exporter is active. The final local transaction alone does not prevent these external races. Focused and Docker-dependent proof of these paths is deferred to the main orchestrator; post-bundle failure reconciliation must continue to follow the asset-storage owner's exact readback/CAS rules. +AR-1.5 full-version publication is currently fail-closed at the public service boundary. `PublishVersionRequest` now carries the exact existing Version, expected state epoch, and selected synchronized commit identity, but the service does not yet have current Account authorization plus authenticated owner-freeze evidence to authorize that selection; selected new requests return `PUBLICATION_AUTHORIZATION_UNAVAILABLE` before reservation, export, or finalization. The legacy request shape is restricted to exact retained terminal replay: succeeded attempts require their original release evidence, failed attempts retain their original failure, and absent or pending attempts cannot be created or promoted without a selection. The command contains the selected-operation guards (including `requirePublicationPending`, captured-operation bundle creation, and same-transaction terminal sealing), and the legacy five-argument bundle method now fails closed instead of rebuilding from mutable revision rows, but no authenticated public caller currently reaches successful new publication. The unused `reserveSelection` helper is not a producer and is not counted as source-capture proof. Fresh publication, source capture, bundle creation, sealing, and ambiguous-outcome behavior remain unproved through a genuine caller; publication-specific focused proof is deferred to the main orchestrator. Do not infer target external-phase race guarantees from these guarded but unreachable mechanics. -The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +The existing publication proof remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams; it does not prove the newly fail-closed selected public path or a complete successful producer. V28 corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. @@ -59,7 +59,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. The `version_asset` mapping table and its Draft-version authoring path are absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The release bundle also lacks canonical target-commit, manifest-schema, and applicable artifact-digest fields. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset mapping and complete release-bundle digest fields remain incomplete. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for revision/version metadata, fail-closed publication gates, and local release-bundle/participant-digest seams; no public successful selected full-version producer is implemented or proved. This does not prove historical revision/version lineage. Post-bundle failure reconciliation, same-commit attestation convergence, complete digest/attestation tuples, and publication-bound generation remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [VersionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java); [game_design_service.proto](../../../protos/game-design/v1/game_design_service.proto); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [VersionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java); [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | @@ -124,7 +124,7 @@ Built-in and authored commands use one provider-backed `TextCommandRegistry` and `TextCommandParser` carries canonical authored IDs into `TextCommandPayload.AuthoredActionInvocation` and resolves authored/extension command IDs even when alias metadata is absent. The authored dispatch handler fails closed on unknown authored action IDs. `HELP` discovery and direct lookup project authored topics from the admitted registry. The obsolete configuration-backed authored-action catalog, parser/help fallback, and test-profile registry fallback have been removed; the published release bundle is the only authored-command authority. -`COMMAND_DEFINITION` revisions accept the first typed schema, reject malformed metadata before persistence, and cannot change after version publication. Full-version publication snapshots ordered validated definitions into the immutable release bundle, and the Game Design control-plane digest changes when their command contract changes. Targeting, cost, and tick-relative cooldown metadata are validated and carried through the shared definition seam, while their general execution semantics remain future work beyond the release-admitted `APPLY_ACTION_STATE` v1 path. `APPLY_ACTION_STATE` v1 is validated at revision and publication time for self-targeting, effect-idempotent replay, bounded duration, and shared-effect-engine modifier grammar. The first live executor supports only release-admitted self-targeted `APPLY_ACTION_STATE` v1; malformed or unsupported effect snapshots and stale session identity fail closed before durable execution. Admission persists release-bundle and version IDs with the command, but durable execution does not yet revalidate those IDs against the currently running release. +`COMMAND_DEFINITION` revisions accept the first typed schema, reject malformed metadata before persistence, and cannot change after version publication. The selected full-version bundle path requires the immutable command source captured for the exact synchronized selection; its legacy five-argument entrypoint fails closed instead of rebuilding from mutable revision rows. The current public publication path cannot yet create a release because its Account authorization and authenticated owner-freeze producer are absent. Targeting, cost, and tick-relative cooldown metadata are validated and carried through the shared definition seam, while their general execution semantics remain future work beyond the release-admitted `APPLY_ACTION_STATE` v1 path. `APPLY_ACTION_STATE` v1 is validated at revision and publication time for self-targeting, effect-idempotent replay, bounded duration, and shared-effect-engine modifier grammar. The first live executor supports only release-admitted self-targeted `APPLY_ACTION_STATE` v1; malformed or unsupported effect snapshots and stale session identity fail closed before durable execution. Admission persists release-bundle and version IDs with the command, but durable execution does not yet revalidate those IDs against the currently running release. The broader authored-action model is not complete. The locked expansion boundary is one version-scoped typed definition seam with implicit `SOURCE` targets and bounded keyed `ActionTargetSet` declarations that reference release-pinned reusable `TargetSelectionPolicy` values. The remaining model distinguishes a reusable `TargetingPolicy` that returns eligible candidates from `TargetSelectionPolicy`, which supplies cardinality and typed selection strategy; target sets retain required/optional behavior and optional player-input slots. Future costs, tick-relative cooldowns, durations, ordered effect steps, and additional effect kinds must remain on the admitted definition snapshot and shared effect/timing boundary rather than per-command scripts or mutable runtime registry reads. @@ -132,9 +132,9 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: export is still tenant-wide and unscoped with only a process-local selection because durable `version_asset` mappings and `version_asset_export_item` snapshots are absent. Version-scoped readiness, lifecycle operation safety, and publication recovery remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records the current status and proof gaps without repeating those owner contracts. -Full-version and script-patch publication use the live durable `publish_attempt`/participant-observation framework. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence with focused proof remains incomplete. End-to-end full-version publication remains blocked because the Game Logic full-version owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; its implementation status is recorded in [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. +Script-patch publication uses the live durable `publish_attempt`/participant-observation framework; the full-version attempt, gate, and finalizer scaffolding remains present, but selected new public requests fail closed before that workflow is started. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence with focused proof remains incomplete. End-to-end full-version publication remains blocked because the Game Logic full-version owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; its implementation status is recorded in [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. -Successful full-version publish still writes only a minimal `published_release_bundle`; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The bounded transaction seam now performs exact bundle/artifact/version readback and keeps an ambiguous attempt pending, but database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +Retained historical full-version releases may contain only a minimal `published_release_bundle`; the current public path cannot create a new release. The selected-operation finalizer requires captured operation/source evidence and same-transaction sealing but remains unreachable until its authorization and owner-freeze producer is implemented; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The selected finalizer is written to perform exact bundle/artifact/version readback and keep an ambiguous attempt pending; because it remains unreachable from an authorized caller, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery are not proved. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 5f849b4040..1fdbf4479b 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -115,6 +115,13 @@ message PublishVersionRequest { string tenant_id = 1; string notes = 2; string publish_request_id = 3; + // Complete together for new publication: the exact existing Draft selection. + // When all selection fields are empty, only a retained terminal legacy retry is eligible. + string version_id = 4; + string expected_version_state_epoch = 5; + string selected_commit_request_id = 6; + string selected_commit_id = 7; + string selected_commit_digest = 8; } message PublishVersionResponse { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java index 971991b867..a283225048 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionService.java @@ -2,6 +2,7 @@ import java.time.LocalDateTime; import java.util.List; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -11,7 +12,12 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; public interface VersionService { - VersionDto publishVersion(String tenantId, String notes, String publishRequestId) + VersionDto publishVersion(PublishIntent intent) throws Exception; + + /** + * Replays retained terminal evidence for a pre-selection request; it cannot start publication. + */ + VersionDto replayLegacyFullVersion(String tenantId, String notes, String publishRequestId) throws Exception; VersionDto publishScriptPatchVersion( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index ed7471a71c..a2701a0d75 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.GameDesignSettingsProtoMapper; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -217,9 +218,40 @@ public void publishVersion( if (request.getPublishRequestId().isBlank()) { throw new IllegalArgumentException("publish_request_id is required"); } - VersionDto version = - versionService.publishVersion( - request.getTenantId(), request.getNotes(), request.getPublishRequestId()); + boolean noSelection = + request.getVersionId().isBlank() + && request.getExpectedVersionStateEpoch().isBlank() + && request.getSelectedCommitRequestId().isBlank() + && request.getSelectedCommitId().isBlank() + && request.getSelectedCommitDigest().isBlank(); + boolean completeSelection = + !request.getVersionId().isBlank() + && !request.getExpectedVersionStateEpoch().isBlank() + && !request.getSelectedCommitRequestId().isBlank() + && !request.getSelectedCommitId().isBlank() + && !request.getSelectedCommitDigest().isBlank(); + VersionDto version; + if (noSelection) { + version = + versionService.replayLegacyFullVersion( + request.getTenantId(), request.getNotes(), request.getPublishRequestId()); + } else if (completeSelection) { + version = + versionService.publishVersion( + new PublishIntent( + canonicalPublicationUuid(request.getTenantId(), "tenant_id"), + canonicalPublicationUuid(request.getVersionId(), "version_id"), + request.getPublishRequestId(), + request.getExpectedVersionStateEpoch(), + request.getNotes(), + canonicalPublicationUuid( + request.getSelectedCommitRequestId(), "selected_commit_request_id"), + canonicalPublicationUuid(request.getSelectedCommitId(), "selected_commit_id"), + request.getSelectedCommitDigest())); + } else { + throw new IllegalArgumentException( + "all selected version, epoch, commit, and digest fields are required together"); + } builder.setVersionId(version.id()); } catch (AdminAuthorizationException ex) { builder.setError( @@ -2041,6 +2073,10 @@ private String publishAttemptErrorCode(RuntimeException failure) { "PUBLISH_ATTEMPT_INCONSISTENT", "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED", "PUBLISH_ATTEMPT_SCOPE_MISMATCH", + "PUBLICATION_AUTHORIZATION_UNAVAILABLE", + "PUBLISH_OWNER_CARRIER_UNAVAILABLE", + "PUBLISH_SELECTION_REQUIRED", + "SELECTED_SOURCE_CAPTURE_UNAVAILABLE", "PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT" -> candidate; default -> null; @@ -2054,6 +2090,14 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private static UUID canonicalPublicationUuid(String value, String field) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } + private void requirePublishedReleaseBundleReadAccess() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java index 311e104fde..8fe910e37f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishWorkflowRequest.java @@ -1,7 +1,18 @@ package net.firedevops.firemud.gamedesign.service.impl; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; + record PublishWorkflowRequest( - String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + String tenantId, + String notes, + String publishRequestId, + String publishWorkflowId, + PublishIntent intent) { + + PublishWorkflowRequest( + String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + this(tenantId, notes, publishRequestId, publishWorkflowId, null); + } /** * Recovers the request id for the legacy command shape that carried only the workflow id. @@ -11,7 +22,10 @@ record PublishWorkflowRequest( * value, and explicit (including blank) request ids are never rewritten. */ PublishWorkflowRequest recoverMissingPublishRequestId() { - if (publishRequestId != null || tenantId == null || publishWorkflowId == null) { + if (intent != null + || publishRequestId != null + || tenantId == null + || publishWorkflowId == null) { return this; } String canonicalPrefix = "publish:" + tenantId + ":publish-request:"; @@ -26,6 +40,7 @@ PublishWorkflowRequest recoverMissingPublishRequestId() { TemporalVersionPublishOrchestrator.workflowId(tenantId, recoveredRequestId))) { return this; } - return new PublishWorkflowRequest(tenantId, notes, recoveredRequestId, publishWorkflowId); + return new PublishWorkflowRequest( + tenantId, notes, recoveredRequestId, publishWorkflowId, intent); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index d4bf88cf3e..e16f6cbb9b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -17,7 +17,6 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; -import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; @@ -33,18 +32,14 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundleService { private final PublishedReleaseBundleRepository repository; - private final RevisionRepository revisionRepository; private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( PublishedReleaseBundleRepository repository, - RevisionRepository revisionRepository, VersionRepository versionRepository, ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); - this.revisionRepository = - Objects.requireNonNull(revisionRepository, "revisionRepository must not be null"); this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); @@ -58,13 +53,8 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { - return createBundle( - version, - publishWorkflowId, - exportedManifest, - generationConfigRevision, - participantDigests, - null); + throw new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); } @Override @@ -93,14 +83,12 @@ private PublishedReleaseBundleDto createBundle( String generationConfigRevision, List participantDigests, WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); Objects.requireNonNull(participantDigests, "participantDigests must not be null"); Optional existing = repository.findByTenantIdAndVersionId(version.tenantId(), version.id()); - if (existing.isPresent() && worldEvidence == null) { - throw new IllegalStateException("published release bundle already exists"); - } if (existing.isPresent()) { PublishedReleaseBundleDto stored = toDto(existing.orElseThrow()); PublishedReleaseBundleContract.requireExactSelectorRetry( @@ -145,13 +133,9 @@ private PublishedReleaseBundleDto createBundle( entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( - worldEvidence == null - ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION - : PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); entity.setWorldPublishedStartLocationEvidenceJson( - worldEvidence == null - ? null - : new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); + new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); entity.setPublishWorkflowId(publishWorkflowId); entity.setManifestHash(exportedManifest.manifestHash()); entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); @@ -162,20 +146,13 @@ private PublishedReleaseBundleDto createBundle( serializeKeys(exportedManifest.requiredManifestAssetKeys())); entity.setParticipantDigestsJson(serializeParticipantDigests(participantDigests)); List commandDefinitions = - worldEvidence == null - ? revisionRepository - .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - version.tenantId(), version.id(), "COMMAND_DEFINITION") - .stream() - .map(revision -> revision.getData()) - .toList() - : repository.requireSelectedCommandDefinitions( - version.tenantId(), version.id(), publishWorkflowId, worldEvidence); + repository.requireSelectedCommandDefinitions( + version.tenantId(), version.id(), publishWorkflowId, worldEvidence); validateDistinctCommandDefinitions(commandDefinitions); entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); entity.setScriptOnly(version.scriptOnly()); entity.setScriptPatchVersion(version.scriptPatchVersion()); - if (worldEvidence != null) toDto(entity); + toDto(entity); return toDto(repository.save(entity)); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index d8c304601e..5516fef3e2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -2,20 +2,25 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.LocalDateTime; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; -import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.GameRepository; @@ -54,6 +59,7 @@ public class VersionPublishCommandServiceImpl { private final VersionAssetArtifactService versionAssetArtifactService; private final PublishedReleaseBundleService publishedReleaseBundleService; private final RecordedParticipantDigestService recordedParticipantDigestService; + private final AuthoredDraftPublishSelectionRepository authoredSelections; public VersionPublishCommandServiceImpl( VersionRepository versionRepository, @@ -66,7 +72,8 @@ public VersionPublishCommandServiceImpl( ControlPlaneDigestService controlPlaneDigestService, VersionAssetArtifactService versionAssetArtifactService, PublishedReleaseBundleService publishedReleaseBundleService, - RecordedParticipantDigestService recordedParticipantDigestService) { + RecordedParticipantDigestService recordedParticipantDigestService, + AuthoredDraftPublishSelectionRepository authoredSelections) { this.versionRepository = versionRepository; this.gameRepository = gameRepository; this.publishAttemptRepository = publishAttemptRepository; @@ -78,6 +85,35 @@ public VersionPublishCommandServiceImpl( this.versionAssetArtifactService = versionAssetArtifactService; this.publishedReleaseBundleService = publishedReleaseBundleService; this.recordedParticipantDigestService = recordedParticipantDigestService; + this.authoredSelections = authoredSelections; + } + + /** Internal plumbing only: a durable selection does not establish creator authorization. */ + PublishWorkflowRequest reserveSelection(PublishIntent intent) { + try { + return publishAttemptService.executeFullVersionTransaction( + () -> { + AuthoredDraftPublishSelection selection = + authoredSelections.reserve(intent).selection(); + return new PublishWorkflowRequest( + selection.target().gameDesignVersionTenantKey(), + intent.notes(), + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + selection.intent()); + }); + } catch (PublishAttemptService.FullVersionTransactionException exception) { + throw exception.causeException(); + } + } + + VersionDto publishFullVersion(PublishWorkflowRequest request) { + PublishWorkflowSnapshot snapshot = reconcileFullVersionPublish(request); + if (!snapshot.isSucceeded()) { + throw publishFailure(snapshot.failureCode(), snapshot.failureMessage()); + } + return versionMapper.toDto(requireTenantVersion(request.tenantId(), snapshot.versionId())); } public VersionDto publishFullVersion( @@ -94,6 +130,9 @@ public VersionDto publishFullVersion( public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowRequest request) { request = request.recoverMissingPublishRequestId(); validateRequestIdentity(request); + if (request.intent() != null) { + requireSelectedIntent(request); + } logger.info( "Reconciling full-version publish workflow tenant={} workflowId={}", request.tenantId(), @@ -101,6 +140,8 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { + requireSelectedIntent(request); + requireCanonicalOwnerPublicationCarrier(request); attempt = reserveDraftAttempt(request); } if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { @@ -111,6 +152,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques // Failed legacy attempts may retain only terminal evidence after their draft was deleted. // Validate their stable scope before entering the draft-dependent compatibility backfill. validateTerminalFullVersionAttempt(attempt, request); + if (request.intent() != null) publishAttemptRepository.requireNoPublicationOperation(attempt); return new PublishWorkflowSnapshot( attempt.getVersionId() == null ? 0L : attempt.getVersionId(), attempt.getVersionNumber(), @@ -119,8 +161,9 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques emptyIfNull(attempt.getFailureCode()), emptyIfNull(attempt.getFailureMessage())); } - attempt = backfillLegacyFullVersionRequestDigest(request, attempt); + requireSelectedIntent(request); validateFullVersionAttempt(attempt, request); + requireCanonicalOwnerPublicationCarrier(request); Version version = requireAttemptVersion(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); @@ -135,6 +178,32 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques throw pendingReconciliation( "pending full-version attempt does not reference a draft version"); } + requireSelectedDraftEpoch(request, version); + return reconcileSelectedPublicationMechanics(request); + } + + private PublishWorkflowSnapshot reconcileSelectedPublicationMechanics( + PublishWorkflowRequest request) { + validateRequestIdentity(request); + requireSelectedIntent(request); + PublishAttempt attempt = + publishAttemptRepository + .findByPublishWorkflowId(request.publishWorkflowId()) + .orElseThrow(() -> pendingReconciliation("selected publish attempt is absent")); + validateFullVersionAttempt(attempt, request); + Version version = requireAttemptVersion(attempt, request); + PublicationReadback existingPublication = readPublication(request, attempt); + if (existingPublication.isComplete()) { + return reconcileCommittedAttempt(request, attempt); + } + if (existingPublication.isPartial()) { + throw pendingReconciliation("selected publication evidence is incomplete"); + } + if (attempt.getStatus() != PublishAttemptStatus.PENDING + || version.getVersionState() != VersionLifecycleState.DRAFT) { + throw pendingReconciliation("selected publication is not the pending Draft operation"); + } + requireSelectedDraftEpoch(request, version); VersionDto dto; List participantDigests; @@ -152,6 +221,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques return failDefinitively(request, attempt, version, null, ex); } try { + assertSelectedCommit(request, participantDigests); publishGateService.assertGatePassed(dto, participantDigests); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { @@ -167,38 +237,33 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } - VersionAssetArtifactStateDto stagedArtifact; - try { - stagedArtifact = - versionAssetArtifactService.stageExport( - request.tenantId(), - version.getId(), - dto.versionNumber(), - request.publishWorkflowId()); - } catch (RuntimeException ex) { - throw pendingReconciliation( - "asset export staging outcome is pending; retry exact publish request", ex); - } - if (stagedArtifact == null - || !Objects.equals(stagedArtifact.tenantId(), request.tenantId()) - || !Objects.equals(stagedArtifact.versionId(), version.getId()) - || stagedArtifact.exportedVersionNumber() != dto.versionNumber() - || !Objects.equals(stagedArtifact.lastWorkflowId(), request.publishWorkflowId()) - || stagedArtifact.stateEpoch() <= 0 - || !("STAGED".equals(stagedArtifact.artifactState()) - || "EXPORTED_UNATTESTED".equals(stagedArtifact.artifactState()))) { - throw pendingReconciliation( - "asset export staging did not confirm the exact pending publish scope; " - + "retry the exact publish request"); + if (existingPublication.isAbsent()) { + try { + VersionAssetArtifactStateDto staged = + versionAssetArtifactService.stageExport( + request.tenantId(), dto.id(), dto.versionNumber(), request.publishWorkflowId()); + VersionAssetArtifactStateDto stagedReadback = + versionAssetArtifactService + .findState(request.tenantId(), dto.id()) + .orElseThrow(() -> pendingReconciliation("asset export intent readback is absent")); + if (staged == null || !staged.equals(stagedReadback)) { + throw pendingReconciliation("asset export intent readback does not match its commit"); + } + verifyStagedIntent(request, attempt, version, stagedReadback); + } catch (RuntimeException ex) { + throw pendingReconciliation("asset export intent commit requires exact readback", ex); + } } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); } catch (AssetExportOutcomePendingException ex) { throw pendingReconciliation( - "asset export outcome is pending; retry exact publish request", ex); + "asset export outcome remains unresolved; retry exact request", ex); } catch (RuntimeException ex) { - return failDefinitively(request, attempt, version, null, ex); + // Export may have committed candidate evidence or earlier immutable objects before failing. + // A deterministic later conflict does not prove that every prior write is resolved. + throw pendingReconciliation("asset export requires exact candidate/write reconciliation", ex); } PublishWorkflowRequest effectiveRequest = request; @@ -258,27 +323,32 @@ private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { } private PublishAttempt createDraftAttempt(PublishWorkflowRequest request) { - Game game = - Optional.ofNullable(gameRepository.findByTenantIdForUpdate(request.tenantId())) - .orElseThrow(() -> new IllegalArgumentException("game not found")); + if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { + throw new IllegalArgumentException("game not found"); + } + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); Optional existingAttempt = - publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()); + publishAttemptRepository.findByPublishWorkflowIdForUpdate(request.publishWorkflowId()); if (existingAttempt.isPresent()) { + validateFullVersionAttempt(existingAttempt.get(), request); return existingAttempt.get(); } - Version version = new Version(); - version.setTenantId(game.getTenantId()); - version.setNotes(request.notes()); - version.setVersionNumber(calculateNextNumber(request.tenantId())); - version.setVersionState(VersionLifecycleState.DRAFT); - version.setVersionStateEpoch(1L); - version.setUpdatedAt(LocalDateTime.now()); - Version saved = versionRepository.save(version); - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(saved.getId()), request.publishRequestId()); + Version saved = + versionRepository + .findByTenantIdAndIdForUpdate( + selection.target().gameDesignVersionTenantKey(), + selection.target().gameDesignVersionRowId()) + .orElseThrow(() -> new IllegalStateException("Selected authored Version is absent")); + if (saved.isScriptOnly() + || saved.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals( + saved.getVersionStateEpoch(), + Long.parseLong(selection.intent().expectedVersionStateEpoch()))) { + throw new IllegalStateException( + "Selected authored Version is no longer the exact reserved Draft"); + } publishAttemptService.createFullVersionAttempt( - versionMapper.toDto(saved), request.publishWorkflowId(), binding.requestDigest()); + versionMapper.toDto(saved), request.publishWorkflowId(), selection.digest()); return publishAttemptRepository .findByPublishWorkflowId(request.publishWorkflowId()) .orElseThrow(() -> new IllegalStateException("publish attempt not found")); @@ -293,21 +363,26 @@ private PublishWorkflowSnapshot finalizeFullVersion( } PublishAttempt attempt = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(attempt, request); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - if (!readPublication(request, attempt).isComplete()) { + publishAttemptRepository.requirePublishedOperation(attempt); + PublicationReadback readback = readPublication(request, attempt); + if (!readback.isComplete()) { throw pendingReconciliation( "succeeded full-version attempt lacks exact committed release evidence"); } + assertCommittedBundleMayMarkSuccess(request, readback); return succeededSnapshot(attempt); } if (attempt.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } - Version version = requireAttemptVersion(attempt, request); + var publicationOperation = publishAttemptRepository.requirePublicationPending(attempt); + + Version version = requireAttemptVersionForUpdate(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); if (existingPublication.isComplete()) { assertCommittedBundleMayMarkSuccess(request, existingPublication); @@ -317,6 +392,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), existingPublication.bundle().participantDigests()); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } if (existingPublication.isPartial()) { @@ -329,6 +405,9 @@ private PublishWorkflowSnapshot finalizeFullVersion( } VersionDto dto = versionMapper.toDto(version); + requireSelectedDraftEpoch(request, version); + assertSelectedCommit(request, participantDigests); + publishGateService.assertGatePassed(dto, participantDigests); publishAttemptService.recordFullVersionParticipantDigests( request.publishWorkflowId(), participantDigests); VersionAssetArtifactStateDto exportedState = @@ -347,9 +426,10 @@ private PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), exportedManifest, generationConfigRevision, - participantDigests); + participantDigests, + publicationOperation); version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L)); version.setUpdatedAt(LocalDateTime.now()); versionRepository.save(version); versionAssetArtifactService.markPublished( @@ -361,6 +441,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( recordedParticipantDigestService.recordVerifiedDigests( dto.tenantId(), PublishType.FULL_VERSION, request.publishWorkflowId(), participantDigests); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } @@ -377,6 +458,7 @@ private PublishWorkflowSnapshot reconcileCommittedAttempt( private PublishWorkflowSnapshot replaySucceededAttempt( PublishWorkflowRequest request, PublishAttempt attempt) { + if (request.intent() != null) publishAttemptRepository.requirePublishedOperation(attempt); PublishedReleaseBundleDto bundle; try { bundle = readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); @@ -390,6 +472,9 @@ private PublishWorkflowSnapshot replaySucceededAttempt( } try { requireExactCommittedBundleIdentity(request, attempt, bundle); + if (request.intent() != null) { + assertCommittedBundleMayMarkSuccess(request, readPublication(request, attempt)); + } } catch (RuntimeException ex) { throw pendingReconciliation( "succeeded full-version attempt release bundle identity does not match", ex); @@ -407,7 +492,7 @@ private void recordVerifiedAndSucceed( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); @@ -415,6 +500,12 @@ private void recordVerifiedAndSucceed( && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { throw pendingReconciliation("full-version attempt is no longer pending"); } + if (current.getStatus() == PublishAttemptStatus.PENDING) { + publishAttemptRepository.requirePublicationPending(current); + } else { + publishAttemptRepository.requirePublishedOperation(current); + } + requireAttemptVersionForUpdate(current, request); PublicationReadback currentReadback = readPublication(request, current); if (!currentReadback.isComplete()) { throw pendingReconciliation( @@ -431,6 +522,7 @@ private void recordVerifiedAndSucceed( currentReadback.bundle().participantDigests()); if (current.getStatus() == PublishAttemptStatus.PENDING) { publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(current, true); } return null; }); @@ -458,7 +550,8 @@ private void assertCommittedBundleMayMarkSuccess( "published release evidence is incomplete; readback/reconciliation is required"); } VersionDto versionDto = versionMapper.toDto(readback.version()); - PublishedReleaseBundleContract.requireSupportedSchemaForRead(readback.bundle()); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); + assertSelectedCommit(request, readback.bundle().participantDigests()); publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); recordedParticipantDigestService.assertMatchesRecordedDigests( request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests()); @@ -480,20 +573,32 @@ private PublishWorkflowSnapshot failDefinitively( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); if (current.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } + publishAttemptRepository.requirePublicationPending(current); + Version currentVersion = requireAttemptVersionForUpdate(current, request); PublicationReadback readback = readPublication(request, current); if (!readback.isAbsent()) { - throw pendingReconciliation( - "publication failure has committed or partial release evidence; reconciliation is required"); + if (!readback.isStagedNoRelease()) { + throw pendingReconciliation( + "publication failure has committed or partial release evidence; reconciliation is required"); + } + if (exportedManifest == null + || !Objects.equals(readback.candidate(), exportedManifest)) { + throw pendingReconciliation( + "staged asset writes remain unresolved; exact export readback is required"); + } } - Version currentVersion = requireAttemptVersion(current, request); if (exportedManifest != null) { + if (!readback.isStagedNoRelease()) { + throw pendingReconciliation( + "exported asset manifest lacks an exact staged intent readback"); + } versionAssetArtifactService.markFailed( request.tenantId(), currentVersion.getId(), @@ -505,10 +610,13 @@ private PublishWorkflowSnapshot failDefinitively( } publishAttemptService.markFullVersionFailed( request.publishWorkflowId(), failureCode, failureMessage); + publishAttemptRepository.sealPublication(current, false); // Approved launch remap sets may reference this failed candidate, so retain the row. return Boolean.TRUE; }); } catch (PublishAttemptService.FullVersionTransactionException ex) { + PublicationReadback winningPublication = readPublication(request, attempt); + if (winningPublication.isComplete()) return reconcileCommittedAttempt(request, attempt); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ex.causeException()); @@ -517,7 +625,8 @@ private PublishWorkflowSnapshot failDefinitively( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ambiguousFailure); } - cleanupExportedAssets(request.tenantId(), version.getVersionNumber(), exportedManifest); + // Immutable candidate keys can be shared with another release. Retain them for the owner + // abandonment/reachability workflow; a failed publication is never deletion authority. return new PublishWorkflowSnapshot( attempt.getVersionId(), attempt.getVersionNumber(), @@ -532,70 +641,21 @@ private void validateRequestIdentity(PublishWorkflowRequest request) { request.tenantId(), request.publishRequestId()); String expectedWorkflowId = TemporalVersionPublishOrchestrator.workflowId( - request.tenantId(), request.publishRequestId()); + request.intent() == null + ? request.tenantId() + : request.intent().canonicalTenantId().toString(), + request.publishRequestId()); if (!Objects.equals(expectedWorkflowId, request.publishWorkflowId())) { throw new IllegalArgumentException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: publish workflow does not match request identity"); } } - /** - * Repairs only the narrow legacy full-version shape that has an exact current request identity. - * - *

V25 could persist the request-digest column but could not compute a digest in SQL. A legacy - * full-version row is therefore retryable only after this application-side check proves the - * tenant, canonical workflow identity, version id, and version number all agree. Script-patch - * rows intentionally have no equivalent compatibility path: their old workflow identifiers do not - * establish the complete request binding, so ordinary validation continues to fail closed. - */ - private PublishAttempt backfillLegacyFullVersionRequestDigest( - PublishWorkflowRequest request, PublishAttempt attempt) { - if (attempt == null - || attempt.getRequestDigest() != null - || attempt.getPublishType() != PublishType.FULL_VERSION - || !Objects.equals(attempt.getTenantId(), request.tenantId()) - || !Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) - || !Objects.equals( - attempt.getPublishWorkflowId(), - TemporalVersionPublishOrchestrator.workflowId( - request.tenantId(), request.publishRequestId())) - || attempt.getBaseVersionId() != null - || attempt.getScriptPatchVersion() != null - || attempt.getVersionId() == null - || attempt.getVersionNumber() <= 0) { - return attempt; - } - - Optional version = - versionRepository.findByTenantIdAndId(request.tenantId(), attempt.getVersionId()); - if (version.isEmpty() - || !Objects.equals(version.get().getTenantId(), request.tenantId()) - || !Objects.equals(version.get().getId(), attempt.getVersionId()) - || version.get().getVersionNumber() != attempt.getVersionNumber() - || version.get().isScriptOnly()) { - return attempt; - } - - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(attempt.getVersionId()), request.publishRequestId()); - return publishAttemptRepository - .backfillFullVersionRequestDigestIfAbsent( - attempt.getId(), - request.tenantId(), - request.publishWorkflowId(), - attempt.getVersionId(), - attempt.getVersionNumber(), - binding.requestDigest()) - .orElse(attempt); - } - private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowRequest request) { validateFullVersionAttemptIdentity(attempt, request); - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full( - request.tenantId(), String.valueOf(attempt.getVersionId()), request.publishRequestId()); - if (!Objects.equals(binding.requestDigest(), attempt.getRequestDigest())) { + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (!Objects.equals(selection.target().gameDesignVersionRowId(), attempt.getVersionId()) + || !Objects.equals(selection.digest(), attempt.getRequestDigest())) { throw new IllegalStateException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: full-version request digest does not match request"); } @@ -608,6 +668,10 @@ private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowR */ private void validateTerminalFullVersionAttempt( PublishAttempt attempt, PublishWorkflowRequest request) { + if (request.intent() != null) { + validateFullVersionAttempt(attempt, request); + return; + } validateFullVersionAttemptIdentity(attempt, request); if (attempt.getRequestDigest() == null) { // Legacy terminal attempts predate the digest column. Their canonical workflow identity, @@ -650,6 +714,22 @@ private Version requireAttemptVersion(PublishAttempt attempt, PublishWorkflowReq return version; } + private Version requireAttemptVersionForUpdate( + PublishAttempt attempt, PublishWorkflowRequest request) { + validateFullVersionAttempt(attempt, request); + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(request.tenantId(), attempt.getVersionId()) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (!Objects.equals(version.getTenantId(), request.tenantId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.isScriptOnly()) { + throw new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match request"); + } + return version; + } + private PublicationReadback readPublication( PublishWorkflowRequest request, PublishAttempt attempt) { Optional version = @@ -664,13 +744,24 @@ private PublicationReadback readPublication( if (bundle == null && artifact == null && version.get().getVersionState() == VersionLifecycleState.DRAFT) { - return PublicationReadback.absent(); + return PublicationReadback.absent(version.get()); + } + if (bundle == null + && version.get().getVersionState() == VersionLifecycleState.DRAFT + && artifact != null) { + try { + ExportedAssetManifest candidate = + verifyStagedIntent(request, attempt, version.get(), artifact); + return PublicationReadback.stagedNoRelease(version.get(), artifact, candidate); + } catch (RuntimeException ex) { + return PublicationReadback.partial(); + } } if (bundle == null || artifact == null) { return PublicationReadback.partial(); } try { - PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); requireExactBundleEvidence(request, attempt, version.get(), bundle); requireExactArtifactEvidence(request, attempt, bundle, artifact); } catch (RuntimeException ex) { @@ -682,6 +773,45 @@ private PublicationReadback readPublication( return PublicationReadback.complete(version.get(), bundle, artifact); } + private ExportedAssetManifest verifyStagedIntent( + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version, + VersionAssetArtifactStateDto artifact) { + if (!Objects.equals(version.getTenantId(), request.tenantId()) + || !Objects.equals(version.getId(), attempt.getVersionId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.isScriptOnly() + || !Objects.equals(artifact.tenantId(), request.tenantId()) + || !Objects.equals(artifact.versionId(), attempt.getVersionId()) + || artifact.exportedVersionNumber() != attempt.getVersionNumber() + || !"STAGED".equals(artifact.artifactState()) + || artifact.stateEpoch() <= 0 + || !Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId())) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_ARTIFACT_SCOPE_MISMATCH"); + } + + ExportedAssetManifest candidate = + versionAssetArtifactService.getExportCandidate(request.tenantId(), attempt.getVersionId()); + if (artifact.manifestHash() == null) { + if (!artifact.exportedManifestAssetKeys().isEmpty() || candidate != null) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); + } + return null; + } + if (candidate == null + || candidate.manifestSchemaVersion() != 1 + || !Objects.equals(candidate.manifestHash(), artifact.manifestHash()) + || !Objects.equals( + candidate.requiredManifestAssetKeys(), artifact.exportedManifestAssetKeys())) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); + } + return candidate; + } + private void requireExactBundleEvidence( PublishWorkflowRequest request, PublishAttempt attempt, @@ -690,7 +820,12 @@ private void requireExactBundleEvidence( requireExactCommittedBundleIdentity(request, attempt, bundle); if (!Objects.equals(version.getTenantId(), bundle.tenantId()) || version.getVersionNumber() != bundle.versionNumber() - || version.isScriptOnly()) { + || version.isScriptOnly() + || (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion()) + && (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId()) + || !Objects.equals( + version.getCanonicalVersionId(), bundle.canonicalVersionId())))) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } } @@ -705,6 +840,39 @@ private void requireExactCommittedBundleIdentity( || bundle.scriptPatchVersion() != null) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); + requireExactSelectedWorldEvidence(request, bundle); + } + } + + private void requireExactSelectedWorldEvidence( + PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) { + // The stored owner payload is historical readback. It does not reconstruct a missing current + // owner freeze/Account permission producer or authorize another publication. + AuthoredDraftPublishSelection selected = requireSelectedIntent(request); + var evidence = bundle.worldPublishedStartLocationEvidence(); + var worldRequest = evidence.request(); + var account = DraftAuthorizationFenceBinding.fromStored(evidence.originalAccountBindingBytes()); + byte[] originalDraft = account.gameDesignBinding(); + if (!Arrays.equals(originalDraft, selected.selectedCommit().canonicalBytes()) + || !Arrays.equals(account.normalizedInput(), originalDraft) + || !selected.intent().selectedCommitDigest().equals(account.inputDigest()) + || !selected.intent().selectedCommitRequestId().equals(account.requestId()) + || !selected.intent().selectedCommitId().equals(account.commitId()) + || !selected.target().canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(worldRequest.canonicalVersionId()) + || !selected.target().canonicalTenantId().equals(bundle.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(bundle.canonicalVersionId()) + || !selected.intent().publishRequestId().equals(worldRequest.publicationRequestId()) + || !request.publishWorkflowId().equals(worldRequest.publishWorkflowId()) + || !selected + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(worldRequest.versionStateEpoch()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_WORLD_SELECTION_MISMATCH"); + } } private void requireExactArtifactEvidence( @@ -712,6 +880,22 @@ private void requireExactArtifactEvidence( PublishAttempt attempt, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { + // Retained terminal history is not backfilled into a complete asset attestation. For a new + // proof-bearing bundle, recovery must compare every original artifact/schema field too. + if (bundle.manifestSchemaVersion() != null) { + ExportedAssetManifest expected = + new ExportedAssetManifest( + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + bundle.artifactDigests()); + if (!Objects.equals( + expected, + versionAssetArtifactService.getExportCandidate( + request.tenantId(), attempt.getVersionId()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_ARTIFACT_SCOPE_MISMATCH"); + } + } if (!Objects.equals(artifact.tenantId(), request.tenantId()) || !Objects.equals(artifact.versionId(), attempt.getVersionId()) || artifact.exportedVersionNumber() != attempt.getVersionNumber() @@ -762,18 +946,25 @@ private record PublicationReadback( ReadbackState state, Version version, PublishedReleaseBundleDto bundle, - VersionAssetArtifactStateDto artifact) { - private static PublicationReadback absent() { - return new PublicationReadback(ReadbackState.ABSENT, null, null, null); + VersionAssetArtifactStateDto artifact, + ExportedAssetManifest candidate) { + private static PublicationReadback absent(Version version) { + return new PublicationReadback(ReadbackState.ABSENT, version, null, null, null); } private static PublicationReadback partial() { - return new PublicationReadback(ReadbackState.PARTIAL, null, null, null); + return new PublicationReadback(ReadbackState.PARTIAL, null, null, null, null); + } + + private static PublicationReadback stagedNoRelease( + Version version, VersionAssetArtifactStateDto artifact, ExportedAssetManifest candidate) { + return new PublicationReadback( + ReadbackState.STAGED_NO_RELEASE, version, null, artifact, candidate); } private static PublicationReadback complete( Version version, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { - return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact); + return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact, null); } private boolean isAbsent() { @@ -784,6 +975,10 @@ private boolean isPartial() { return state == ReadbackState.PARTIAL; } + private boolean isStagedNoRelease() { + return state == ReadbackState.STAGED_NO_RELEASE; + } + private boolean isComplete() { return state == ReadbackState.COMPLETE; } @@ -791,16 +986,71 @@ private boolean isComplete() { private enum ReadbackState { ABSENT, + STAGED_NO_RELEASE, PARTIAL, COMPLETE } - private int calculateNextNumber(String tenantId) { - return versionRepository - .findTopByTenantIdOrderByVersionNumberDesc(tenantId) - .map(Version::getVersionNumber) - .orElse(0) - + 1; + private AuthoredDraftPublishSelection requireSelectedIntent(PublishWorkflowRequest request) { + if (request.intent() == null) { + throw new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: retained terminal readback is the only unselected operation"); + } + AuthoredDraftPublishSelection selection = + authoredSelections + .readByPublishRequest(request.intent().canonicalTenantId(), request.publishRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: exact durable selection is absent")) + .selection(); + if (!selection.intent().equals(request.intent()) + || !selection.target().gameDesignVersionTenantKey().equals(request.tenantId()) + || !selection.intent().notes().equals(request.notes()) + || !selection.intent().publishRequestId().equals(request.publishRequestId())) { + throw new IllegalStateException( + "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: exact original selection intent differs"); + } + return selection; + } + + private void requireCanonicalOwnerPublicationCarrier(PublishWorkflowRequest request) { + if (request.intent() != null) { + throw new IllegalStateException( + "PUBLISH_OWNER_CARRIER_UNAVAILABLE: current Account authorization and authenticated selected-source owner freeze are unavailable"); + } + } + + private void requireSelectedDraftEpoch(PublishWorkflowRequest request, Version version) { + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (!Objects.equals( + version.getVersionStateEpoch(), + Long.parseLong(selection.intent().expectedVersionStateEpoch()))) { + throw new IllegalStateException( + "VERSION_STATE_EPOCH_STALE: Draft differs from its exact original publication selection"); + } + } + + private void assertSelectedCommit( + PublishWorkflowRequest request, List digests) { + if (request.intent() == null) { + return; // Historical terminal readback does not invent missing selection evidence. + } + AuthoredDraftPublishSelection selection = requireSelectedIntent(request); + if (digests == null + || digests.stream() + .anyMatch( + digest -> + digest == null + || !selection + .selectedCommit() + .commitId() + .toString() + .equals(digest.appliedCommitId()))) { + throw new PublishGateFailureException( + PublishGateFailureCode.APPLIED_COMMIT_MISMATCH, + "Every participant must report the exact selected authored Draft commit"); + } } private PublishedReleaseBundleDto readPublishedReleaseBundle(String tenantId, long versionId) { @@ -853,23 +1103,6 @@ private RuntimeException publishFailure(String failureCode, String failureMessag : failureMessage); } - private void cleanupExportedAssets( - String tenantId, int versionNumber, ExportedAssetManifest exportedManifest) { - if (exportedManifest == null) { - return; - } - try { - assetExportService.deleteExportedAssets( - tenantId, versionNumber, exportedManifest.requiredManifestAssetKeys()); - } catch (RuntimeException cleanupEx) { - logger.warn( - "Failed cleanup of exported assets for tenant {} version {} after publish failure: {}", - tenantId, - versionNumber, - cleanupEx.getMessage()); - } - } - private Version requireTenantVersion(String tenantId, long versionId) { return versionRepository .findByTenantIdAndId(tenantId, versionId) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index ad638c3b19..162f14b960 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -120,19 +121,23 @@ public VersionServiceImpl( @Override @Timed(value = "gamedesign.version.publish") - public VersionDto publishVersion(String tenantId, String notes, String publishRequestId) { - logger.info("Publishing version for tenant {}", tenantId); - PublicationDigestRequestBinding.validatePublicationIdentity(tenantId, publishRequestId); - if (temporalPublishOrchestrator.isPresent()) { - return temporalPublishOrchestrator - .get() - .publishFullVersion(tenantId, notes, publishRequestId); - } - return publishCommandService.publishFullVersion( - tenantId, - notes, - publishRequestId, - TemporalVersionPublishOrchestrator.workflowId(tenantId, publishRequestId)); + public VersionDto publishVersion(PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + // Admin role and caller-selected commit identifiers do not prove current creator authority or + // the authenticated owner freeze required by full-version publication. + throw new IllegalStateException( + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: exact current Account authorization and owner freeze are required"); + } + + @Override + @Timed(value = "gamedesign.version.replayLegacyFullVersion") + public VersionDto replayLegacyFullVersion( + String tenantId, String notes, String publishRequestId) { + String workflowId = TemporalVersionPublishOrchestrator.workflowId(tenantId, publishRequestId); + // The command permits this old request shape only when the exact workflow already has a + // terminal attempt. A fresh or pending legacy request has no selected immutable source and + // is rejected before export, finalization, or attempt creation. + return publishCommandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); } @Override diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index ffba052595..a6f2483ebc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -12,6 +12,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; @@ -90,6 +91,8 @@ class GameDesignGrpcServiceTest { private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); @@ -310,11 +313,55 @@ void publishVersionRequiresPublishRequestId() { } @Test - void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + void publishVersionRejectsPartialSelectedSourceIdentity() { + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion( + PublishVersionRequest.newBuilder() + .setTenantId(CANONICAL_TENANT_ID.toString()) + .setNotes("notes") + .setPublishRequestId("publish-request-1") + .setVersionId(CANONICAL_VERSION_ID.toString()) + .build(), + observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); + } + + @Test + void publishVersionMapsMissingOwnerAuthorizationToExplicitDenial() throws Exception { + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow( new IllegalStateException( - "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match")); + "PUBLICATION_AUTHORIZATION_UNAVAILABLE: exact current authorization required")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); + } + + assertEquals("PUBLICATION_AUTHORIZATION_UNAVAILABLE", ref.get().getError().getCode()); + } + + @Test + void publishVersionLegacyShapeOnlyUsesRetainedTerminalReplay() throws Exception { + Mockito.when(versionService.replayLegacyFullVersion("tenant-1", "notes", "legacy-1")) + .thenReturn( + new VersionDto( + 10L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -322,11 +369,29 @@ void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { PublishVersionRequest.newBuilder() .setTenantId("tenant-1") .setNotes("notes") - .setPublishRequestId("publish-request-1") + .setPublishRequestId("legacy-1") .build(), observerFor(ref)); } + assertEquals(10L, ref.get().getVersionId()); + Mockito.verify(versionService).replayLegacyFullVersion("tenant-1", "notes", "legacy-1"); + Mockito.verify(versionService, Mockito.never()) + .publishVersion(Mockito.any(PublishIntent.class)); + } + + @Test + void publishVersionMapsKnownPublishAttemptStateFailures() throws Exception { + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) + .thenThrow( + new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match")); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); + } + assertEquals("PUBLISH_ATTEMPT_SCOPE_MISMATCH", ref.get().getError().getCode()); } @@ -342,18 +407,12 @@ void publishVersionMapsTemporalKnownGateFailureCode() throws Exception { "FAILED", PublishGateFailureCode.PARTICIPANT_SET_MISMATCH.name(), "participant set mismatch")); - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow(gateFailure); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("PARTICIPANT_SET_MISMATCH", ref.get().getError().getCode()); @@ -361,20 +420,14 @@ void publishVersionMapsTemporalKnownGateFailureCode() throws Exception { @Test void publishVersionMapsKnownIllegalArgumentPublishAttemptCode() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow( new IllegalArgumentException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: publish workflow does not match request")); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("PUBLISH_ATTEMPT_IDENTITY_CONFLICT", ref.get().getError().getCode()); @@ -500,18 +553,12 @@ void publishScriptPatchVersionMapsUnknownIllegalArgumentToInvalidArgument() thro @Test void publishVersionKeepsUnknownIllegalStateFailuresInternal() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "publish-request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("publish-request-1"))) .thenThrow(new IllegalStateException("unexpected internal state")); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("publish-request-1") - .build(), - observerFor(ref)); + service.publishVersion(selectedPublishRequest("publish-request-1"), observerFor(ref)); } assertEquals("INTERNAL", ref.get().getError().getCode()); @@ -568,18 +615,12 @@ void publishScriptPatchVersionMapsReplayedFailureCodeAndMessage() throws Excepti @Test void publishVersionMapsPendingReconciliationToStableApplicationError() throws Exception { - Mockito.when(versionService.publishVersion("tenant-1", "notes", "request-1")) + Mockito.when(versionService.publishVersion(selectedIntent("request-1"))) .thenThrow(new PublishAttemptPendingReconciliationException()); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.publishVersion( - PublishVersionRequest.newBuilder() - .setTenantId("tenant-1") - .setNotes("notes") - .setPublishRequestId("request-1") - .build(), - observerFor(ref)); + service.publishVersion(selectedPublishRequest("request-1"), observerFor(ref)); } assertEquals( @@ -1463,6 +1504,31 @@ private void underLaunchPeer(String serviceName, Runnable operation) { Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } + private static PublishIntent selectedIntent(String requestId) { + return new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + requestId, + "1", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); + } + + private static PublishVersionRequest selectedPublishRequest(String requestId) { + return PublishVersionRequest.newBuilder() + .setTenantId(CANONICAL_TENANT_ID.toString()) + .setVersionId(CANONICAL_VERSION_ID.toString()) + .setExpectedVersionStateEpoch("1") + .setSelectedCommitRequestId("33333333-3333-4333-8333-333333333333") + .setSelectedCommitId("44444444-4444-4444-8444-444444444444") + .setSelectedCommitDigest("sha256:" + "a".repeat(64)) + .setNotes("notes") + .setPublishRequestId(requestId) + .build(); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index fabdc0d60f..a14d6208f8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -258,8 +258,7 @@ private VersionDto selectorVersion() { void setUp() { MockitoAnnotations.openMocks(this); service = - new PublishedReleaseBundleServiceImpl( - repository, revisionRepository, versionRepository, new ObjectMapper()); + new PublishedReleaseBundleServiceImpl(repository, versionRepository, new ObjectMapper()); Version source = new Version(); source.setId(7L); source.setTenantId("tenant-1"); @@ -269,82 +268,15 @@ void setUp() { } @Test - void createFullVersionBundlePersistsImmutableAttestation() { - VersionDto version = - new VersionDto( - 7L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now()); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision commandDefinition = new Revision(); - commandDefinition.setData(validCommandDefinition()); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(commandDefinition)); - when(repository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle entity = invocation.getArgument(0); - entity.setId(11L); - entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); - return entity; - }); - - var dto = - service.createFullVersionBundle( - version, - "workflow-1", - logoManifest(), - "genrev-1", - List.of( - new PublishParticipantDigestDto( - "GAME_LOGIC", - "7", - null, - "version:7", - "digest-logic", - 1, - "ability-schema-v1", - null, - null), - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null))); + void legacyFullVersionCannotCreateV1BundleFromMutableRevisions() { + assertThatThrownBy( + () -> + service.createFullVersionBundle( + version(), "workflow-1", logoManifest(), "genrev-1", List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); - assertEquals(11L, dto.id()); - assertEquals("tenant-1", dto.tenantId()); - assertEquals(7L, dto.versionId()); - assertEquals(MANIFEST_HASH, dto.manifestHash()); - assertEquals(1, dto.manifestSchemaVersion()); - assertEquals(List.of(logoProof()), dto.artifactDigests()); - assertEquals("genrev-1", dto.generationConfigRevision()); - assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); - assertEquals(2, dto.participantDigests().size()); - assertEquals("GAME_LOGIC", dto.participantDigests().getFirst().participantKey()); - assertEquals("version:7", dto.participantDigests().getFirst().appliedCommitId()); - assertEquals("digest-logic", dto.participantDigests().getFirst().contentDigest()); - assertEquals(1, dto.participantDigests().getFirst().digestSchemaVersion()); - assertEquals("ability-schema-v1", dto.participantDigests().getFirst().abilitySchemaDigest()); - assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); - assertEquals("v1", dto.attestationSchemaVersion()); - assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); - assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); - assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); - org.mockito.Mockito.verify(repository) - .save( - org.mockito.ArgumentMatchers.argThat( - saved -> - sourceIdentity().getCanonicalTenantId().equals(saved.getCanonicalTenantId()) - && sourceIdentity() - .getCanonicalVersionId() - .equals(saved.getCanonicalVersionId()))); + org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); } @Test @@ -372,13 +304,15 @@ void retainedBundleWithoutCanonicalIdentityStaysAbsent() { private Version sourceIdentity() { Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); return version; } @Test - void createFullVersionBundleRejectsDuplicateAttestation() { + void legacyBundleEntryPointRejectsWithoutSelectedPublicationEvidence() { VersionDto version = new VersionDto( 7L, @@ -392,14 +326,13 @@ void createFullVersionBundleRejectsDuplicateAttestation() { "notes", LocalDateTime.now(), LocalDateTime.now()); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) - .thenReturn(Optional.of(new PublishedReleaseBundle())); - - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + version, "workflow-1", emptyManifest(), "genrev-1", List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); } @Test @@ -413,7 +346,7 @@ void optionalReadDistinguishesMissingBundleWhileRequiredReadStillFails() { } @Test - void createFullVersionBundleRejectsDuplicateCommandDefinitionAlias() { + void legacyBundleEntryPointDoesNotReadMutableCommandRevisionRows() { VersionDto version = new VersionDto( 7L, @@ -427,73 +360,47 @@ void createFullVersionBundleRejectsDuplicateCommandDefinitionAlias() { "notes", LocalDateTime.now(), LocalDateTime.now()); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); Revision first = new Revision(); first.setData(commandDefinition("salute", "hail")); - Revision second = new Revision(); - second.setData(commandDefinition("greet", "HAIL")); when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(first, second)); + .thenReturn(List.of(first)); - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())); - } - - @Test - void createFullVersionBundleRejectsDuplicateCanonicalCommandIds() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision first = new Revision(); - first.setData(commandDefinition("salute", "hail")); - Revision second = new Revision(); - second.setData(commandDefinition("SALUTE", "greet")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(first, second)); - - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); - } - - @Test - void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision first = new Revision(); - first.setData(commandDefinition("salute", "greet")); - Revision second = new Revision(); - second.setData(commandDefinition("hail", "SALUTE")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(first, second)); - - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + version, "workflow-1", emptyManifest(), "genrev-1", List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(repository, versionRepository); + org.mockito.Mockito.verify(revisionRepository, org.mockito.Mockito.never()) + .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, "COMMAND_DEFINITION"); } @Test - void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { - VersionDto version = version(); + void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision commandDefinition = new Revision(); - commandDefinition.setData(validCommandDefinition().replace("\"value\":1", "\"value\":\"one\"")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(commandDefinition)); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) + .thenReturn(Optional.of(sourceIdentity())); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); - assertThrows( - IllegalArgumentException.class, - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); } private VersionDto version() { @@ -511,6 +418,99 @@ private VersionDto version() { LocalDateTime.now()); } + @Test + void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-issued-reference-11"); + return saved; + }); + + var dto = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + logoManifest(), + "genrev-1", + participants, + evidence); + + assertEquals(11L, dto.id()); + assertEquals("tenant-1", dto.tenantId()); + assertEquals(7L, dto.versionId()); + assertEquals(8, dto.versionNumber()); + assertEquals(MANIFEST_HASH, dto.manifestHash()); + assertEquals(1, dto.manifestSchemaVersion()); + assertEquals(List.of(logoProof()), dto.artifactDigests()); + assertEquals("genrev-1", dto.generationConfigRevision()); + assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); + assertEquals(participants, dto.participantDigests()); + assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); + assertEquals("v2", dto.attestationSchemaVersion()); + assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); + assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); + assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); + assertThat(dto.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + } + + @Test + void selectedFullVersionBundleRejectsDuplicateCommandDefinitionAlias() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "hail"), commandDefinition("greet", "HAIL")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsDuplicateCanonicalCommandIds() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "hail"), commandDefinition("SALUTE", "greet")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsCanonicalIdAndAliasCollisions() throws Exception { + assertSelectedCommandsRejected( + List.of(commandDefinition("salute", "greet"), commandDefinition("hail", "SALUTE")), + IllegalStateException.class); + } + + @Test + void selectedFullVersionBundleRejectsMalformedCommandEffectDeclaration() throws Exception { + assertSelectedCommandsRejected( + List.of(validCommandDefinition().replace("\"value\":1", "\"value\":\"one\"")), + IllegalArgumentException.class); + } + + private void assertSelectedCommandsRejected( + List commandDefinitions, Class exceptionType) + throws Exception { + var evidence = selectorEvidence(); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(commandDefinitions); + + assertThrows( + exceptionType, + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + } + private static ExportedAssetManifest emptyManifest() { return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java index 5077165234..6739464bd4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java @@ -1,12 +1,54 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; +import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.mapper.VersionMapper; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportService; +import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.PublishAttemptService; +import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; class TemporalVersionPublishActivitiesImplTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + @Test void pendingReconciliationIsReturnedAsNonterminalSnapshot() { VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); @@ -28,4 +70,150 @@ void pendingReconciliationIsReturnedAsNonterminalSnapshot() { "committed publication readback could not be reconciled", snapshot.failureMessage()); assertEquals(false, snapshot.isTerminal()); } + + @Test + void registeredActivityDeniesFreshAndPendingSelectedAndLegacyRequestsBeforeMutation() { + assertActivityDeniesBeforeMutation(false, false); + assertActivityDeniesBeforeMutation(false, true); + assertActivityDeniesBeforeMutation(true, false); + assertActivityDeniesBeforeMutation(true, true); + } + + private void assertActivityDeniesBeforeMutation(boolean selected, boolean pending) { + VersionRepository versions = mock(VersionRepository.class); + GameRepository games = mock(GameRepository.class); + PublishAttemptRepository attempts = mock(PublishAttemptRepository.class); + AssetExportService assetExports = mock(AssetExportService.class); + PublishAttemptService attemptService = mock(PublishAttemptService.class); + PublishGateService gates = mock(PublishGateService.class); + ControlPlaneDigestService controlPlane = mock(ControlPlaneDigestService.class); + VersionAssetArtifactService artifacts = mock(VersionAssetArtifactService.class); + PublishedReleaseBundleService bundles = mock(PublishedReleaseBundleService.class); + RecordedParticipantDigestService recordedDigests = mock(RecordedParticipantDigestService.class); + AuthoredDraftPublishSelectionRepository selections = + mock(AuthoredDraftPublishSelectionRepository.class); + VersionPublishCommandServiceImpl commandService = + new VersionPublishCommandServiceImpl( + versions, + games, + attempts, + Mappers.getMapper(VersionMapper.class), + assetExports, + attemptService, + gates, + controlPlane, + artifacts, + bundles, + recordedDigests, + selections); + + SelectionSnapshot reservation = selected ? selectedReservation() : null; + PublishIntent intent = selected ? reservation.selection().intent() : null; + String publishRequestId = selected ? intent.publishRequestId() : "request-1"; + String workflowId = + TemporalVersionPublishOrchestrator.workflowId( + selected ? intent.canonicalTenantId().toString() : "tenant-1", publishRequestId); + PublishWorkflowRequest request = + new PublishWorkflowRequest("tenant-1", "notes", publishRequestId, workflowId, intent); + if (selected) { + when(selections.readByPublishRequest(intent.canonicalTenantId(), publishRequestId)) + .thenReturn(Optional.of(reservation)); + } + PublishAttempt attempt = null; + if (pending) { + attempt = new PublishAttempt(); + attempt.setTenantId("tenant-1"); + attempt.setVersionId(10L); + attempt.setVersionNumber(1); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setPublishWorkflowId(workflowId); + attempt.setStatus(PublishAttemptStatus.PENDING); + attempt.setRequestDigest(selected ? reservation.selection().digest() : null); + when(attempts.findByPublishWorkflowId(workflowId)).thenReturn(Optional.of(attempt)); + } else { + when(attempts.findByPublishWorkflowId(workflowId)).thenReturn(Optional.empty()); + } + + assertThrows( + IllegalStateException.class, + () -> new TemporalVersionPublishActivitiesImpl(commandService).reconcile(request)); + + verify(attempts, never()).save(any(PublishAttempt.class)); + verify(attempts, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(attemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(attemptService, never()).executeFullVersionTransaction(any()); + verify(versions, never()).save(any(Version.class)); + verify(assetExports, never()).exportAssets(any(String.class), any(Integer.class)); + verify(selections, never()).reserve(any(PublishIntent.class)); + verifyNoInteractions( + versions, + games, + assetExports, + attemptService, + gates, + controlPlane, + artifacts, + bundles, + recordedDigests); + if (pending) assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + } + + private SelectionSnapshot selectedReservation() { + UUID requestId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID commitId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-1", + List.of( + new RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "1"))); + PublishIntent intent = + new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "request-1", + "1", + "notes", + requestId, + commitId, + binding.digest()); + VisibilityFence fence = + new VisibilityFence( + target, + requestId, + commitId, + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + // The retained source selection is not Account permission or an authenticated World freeze. + return new SelectionSnapshot(selection, OffsetDateTime.parse("2026-10-08T00:00:00Z")); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index c69756353f..f778fb67a5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -6,16 +6,32 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; @@ -69,6 +85,8 @@ class VersionPublishCommandServiceImplTest { @Mock private VersionAssetArtifactService versionAssetArtifactService; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private RecordedParticipantDigestService recordedParticipantDigestService; + @Mock private AuthoredDraftPublishSelectionRepository authoredSelections; + @Mock private WorldPublishedStartLocationEvidence capturedWorldPublicationEvidence; private VersionPublishCommandServiceImpl service; @@ -80,6 +98,8 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(publishAttemptRepository.requirePublicationPending(any(PublishAttempt.class))) + .thenReturn(capturedWorldPublicationEvidence); when(versionAssetArtifactService.stageExport( any(String.class), any(Long.class), any(Integer.class), any(String.class))) .thenAnswer( @@ -119,365 +139,170 @@ void setup() { controlPlaneDigestService, versionAssetArtifactService, publishedReleaseBundleService, - recordedParticipantDigestService); + recordedParticipantDigestService, + authoredSelections); } @Test - void publishFullVersionUsesTenantScopedVersionSequence() { - Game game = new Game(); - game.setId(1L); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - - Version latest = new Version(); - latest.setId(9L); - latest.setTenantId("tenant-1"); - latest.setVersionNumber(7); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) - .thenReturn(Optional.of(latest)); - - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(8); - savedDraft.setNotes("notes"); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - Version savedPublished = new Version(); - savedPublished.setId(10L); - savedPublished.setTenantId("tenant-1"); - savedPublished.setVersionNumber(8); - savedPublished.setNotes("notes"); - savedPublished.setVersionState(VersionLifecycleState.PUBLISHED); - savedPublished.setVersionStateEpoch(2L); - savedPublished.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft, savedPublished); - - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(8); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.empty(), Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn( - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedDraft), - Optional.of(savedPublished)); - - ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); - when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); - List participantDigests = - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); - when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) - .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); - when(versionAssetArtifactService.markExportedUnattested( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "EXPORTED_UNATTESTED", - 1L, - MANIFEST_HASH, - "workflow-1", - null, - null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); - when(publishedReleaseBundleService.createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class))) - .thenReturn( - publishedReleaseBundleDto( - 1L, - "tenant-1", - 10L, - 8, - "v1", - "publish:tenant-1:publish-request:workflow-1", - MANIFEST_HASH, - List.of("logo.png", "manifest.json"), - participantDigests, - "genrev-tenant-1-10", - false, - null, - LocalDateTime.now())); - when(versionAssetArtifactService.markPublished( - any(String.class), - any(Long.class), - any(Long.class), - any(String.class), - any(String.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "PUBLISHED", - 2L, - MANIFEST_HASH, - "workflow-1", - null, - null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); + void publishFullVersionRequiresOriginalSelectedDraft() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; - VersionDto dto = - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1"); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); - verify(publishAttemptService) + assertTrue(thrown.getMessage().startsWith("PUBLISH_SELECTION_REQUIRED")); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptService, never()) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); - verify(assetExportService).exportAssets("tenant-1", 8); - verify(recordedParticipantDigestService) - .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - - InOrder publishOrder = - inOrder( - publishGateService, - recordedParticipantDigestService, - versionAssetArtifactService, - assetExportService, - publishAttemptService); - publishOrder - .verify(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); - publishOrder - .verify(recordedParticipantDigestService) - .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); - publishOrder - .verify(versionAssetArtifactService) - .stageExport("tenant-1", 10L, 8, "publish:tenant-1:publish-request:workflow-1"); - publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); - publishOrder - .verify(publishAttemptService) - .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); } @Test - void publishFullVersionPropagatesTypedPublishGateFailures() { - Game game = new Game(); - game.setId(1L); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + void selectedPublishRequestRequiresDurableOriginalSelection() { + PublishIntent intent = selectedIntent(); + String workflowId = + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()); + PublishWorkflowRequest request = + new PublishWorkflowRequest( + "tenant-1", intent.notes(), intent.publishRequestId(), workflowId, intent); + + when(authoredSelections.readByPublishRequest( + intent.canonicalTenantId(), intent.publishRequestId())) .thenReturn(Optional.empty()); - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(savedDraft)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn( - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null))); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")) - .when(recordedParticipantDigestService) - .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); + assertTrue(thrown.getMessage().startsWith("PUBLISH_SELECTION_REQUIRED")); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).save(any(Version.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void legacyPendingAttemptCannotBePromotedWithoutOriginalSelection() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + attempt.setRequestDigest(null); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); - PublishGateFailureException thrown = + IllegalStateException thrown = assertThrows( - PublishGateFailureException.class, + IllegalStateException.class, () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); - verify(publishAttemptService) - .markFullVersionFailed( + assertTrue(thrown.getMessage().startsWith("PUBLISH_SELECTION_REQUIRED")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptRepository, never()) + .backfillFullVersionRequestDigestIfAbsent( + any(Long.class), any(String.class), - org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), - org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).save(any(Version.class)); } @Test - void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { - Game game = new Game(); - game.setId(1L); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) + void freshSelectedRequestIsDeniedBeforeReservationOrPublicationMutation() { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) .thenReturn(Optional.empty()); - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(savedDraft)); + assertTrue(thrown.getMessage().startsWith("PUBLISH_OWNER_CARRIER_UNAVAILABLE:")); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } - List participantDigests = - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected")) - .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + @Test + void pendingSelectedRequestIsDeniedBeforePublicationMutation() { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = selectedAttempt(reservation, request, 1); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); - PublishGateFailureException thrown = + IllegalStateException thrown = assertThrows( - PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertTrue(thrown.getMessage().startsWith("PUBLISH_OWNER_CARRIER_UNAVAILABLE:")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); verify(publishAttemptService, never()) - .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { - Game game = new Game(); - game.setId(1L); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findTopByTenantIdOrderByVersionNumberDesc("tenant-1")) - .thenReturn(Optional.empty()); - - Version savedDraft = new Version(); - savedDraft.setId(10L); - savedDraft.setTenantId("tenant-1"); - savedDraft.setVersionNumber(1); - savedDraft.setVersionState(VersionLifecycleState.DRAFT); - savedDraft.setVersionStateEpoch(1L); - savedDraft.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.save(any(Version.class))).thenReturn(savedDraft); - - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId("tenant-1"); - attempt.setVersionId(10L); - attempt.setVersionNumber(1); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setPublishWorkflowId("publish:tenant-1:publish-request:workflow-1"); - attempt.setRequestDigest( - PublicationDigestRequestBinding.full("tenant-1", "10", "workflow-1").requestDigest()); - when(publishAttemptRepository.findByPublishWorkflowId( - "publish:tenant-1:publish-request:workflow-1")) - .thenReturn(Optional.empty(), Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(savedDraft)); - when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(exportedManifest(List.of("manifest.json"))); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn( - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest-1", 1, null, null))); - when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) - .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); - when(versionAssetArtifactService.markExportedUnattested( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class))) - .thenReturn( - new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "EXPORTED_UNATTESTED", - 1L, - MANIFEST_HASH, - "workflow-1", - null, - null, - LocalDateTime.now(), - List.of("manifest.json"))); - org.mockito.Mockito.doThrow(new IllegalStateException("bundle failed")) - .when(publishedReleaseBundleService) - .createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class)); + void legacyFreshRequestDoesNotExportOrDeleteCandidateAssets() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; assertThrows( IllegalStateException.class, - () -> - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); } @Test @@ -733,13 +558,383 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { } @Test - void uncertainAssetExportRemainsPendingForExactRetry() { + void nonCanonicalLegacyFullWorkflowFailsBeforeCompatibilityRewrite() { + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, "legacy-random-workflow"); + attempt.setId(101L); + attempt.setRequestDigest(null); + + assertThrows( + IllegalArgumentException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "legacy-random-workflow"))); + + verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); + verify(publishAttemptRepository, never()) + .backfillFullVersionRequestDigestIfAbsent( + any(Long.class), + any(String.class), + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class)); + } + + @Test + void missingLegacyPublishRequestIdIsRecoveredFromCanonicalWorkflowId() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.FAILED, 10L, 1, workflowId); + attempt.setRequestDigest(null); + attempt.setFailureCode("PUBLISH_FAILED"); + attempt.setFailureMessage("legacy publish failure"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + + PublishWorkflowSnapshot snapshot = + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", null, workflowId)); + + assertEquals("FAILED", snapshot.status()); + assertEquals("PUBLISH_FAILED", snapshot.failureCode()); + verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); + } + + @Test + void missingLegacyPublishRequestIdDoesNotCrossTenantWorkflowPrefix() { + String workflowId = "publish:tenant-2:publish-request:workflow-1"; + + assertThrows( + IllegalArgumentException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", null, workflowId))); + + verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); + } + + @Test + void mismatchedRequestDigestCannotReplaySucceededAttempt() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); + attempt.setRequestDigest("0".repeat(64)); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + + assertThrows( + IllegalStateException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(publishedReleaseBundleService, never()) + .findPublishedReleaseBundle(any(String.class), any(Long.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void reflectiveUnitHarnessReconcilesSelectedExistingVersionWithCapturedOperation() { + SelectedPublishFixture fixture = selectedPublishFixture(8); + Version version = fixture.version(); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); + List participantDigests = participantDigests(); + ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, version); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 8, request.publishWorkflowId())) + .thenReturn(staged); + when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 8, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("logo.png", "manifest.json"))); + when(publishedReleaseBundleService.createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence))) + .thenReturn( + publishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 8, + "v1", + request.publishWorkflowId(), + MANIFEST_HASH, + List.of("logo.png", "manifest.json"), + participantDigests, + "genrev-tenant-1-10", + false, + null, + LocalDateTime.now())); + when(versionAssetArtifactService.markPublished( + any(String.class), + any(Long.class), + any(Long.class), + any(String.class), + any(String.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 8, + "PUBLISHED", + 3L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("logo.png", "manifest.json"))); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); + + assertEquals("SUCCEEDED", snapshot.status()); + assertEquals(10L, snapshot.versionId()); + assertEquals(VersionLifecycleState.PUBLISHED, version.getVersionState()); + assertEquals(2L, version.getVersionStateEpoch()); + verify(versionRepository, never()).findTopByTenantIdOrderByVersionNumberDesc("tenant-1"); + verify(versionRepository).save(version); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService) + .recordFullVersionParticipantDigests(request.publishWorkflowId(), participantDigests); + verify(publishAttemptRepository).requirePublicationPending(attempt); + verify(publishAttemptRepository).sealPublication(attempt, true); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + + InOrder publishOrder = + inOrder( + publishGateService, + recordedParticipantDigestService, + versionAssetArtifactService, + assetExportService, + publishedReleaseBundleService, + publishAttemptService, + publishAttemptRepository); + publishOrder + .verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(PublishType.FULL_VERSION), + org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 8, request.publishWorkflowId()); + publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); + publishOrder + .verify(publishAttemptService) + .recordFullVersionParticipantDigests( + org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()), + org.mockito.ArgumentMatchers.eq(participantDigests)); + publishOrder + .verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + publishOrder.verify(publishAttemptRepository).sealPublication(attempt, true); + } + + @Test + void publishFullVersionPropagatesTypedPublishGateFailures() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, + "recorded digest mismatch")) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); + verify(publishAttemptService) + .markFullVersionFailed( + org.mockito.ArgumentMatchers.eq(fixture.request().publishWorkflowId()), + org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), + org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + List participantDigests = participantDigests(); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); + verify(publishAttemptService, never()) + .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + } + + @Test + void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + VersionAssetArtifactStateDto exportedState = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenReturn(staged); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn(exportedState); + org.mockito.Mockito.doThrow(new IllegalStateException("bundle commit outcome is unknown")) + .when(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(capturedWorldPublicationEvidence)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("incomplete evidence")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @ParameterizedTest + @EnumSource( + value = Status.Code.class, + names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code statusCode) { + SelectedPublishFixture fixture = selectedPublishFixture(1); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request())); + + assertTrue(thrown.getMessage().contains("temporarily unavailable")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void uncertainAssetExportRemainsPendingForExactRetry() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) + .thenReturn(staged); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); @@ -749,12 +944,10 @@ void uncertainAssetExportRemainsPendingForExactRetry() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertTrue(thrown.getMessage().contains("asset export outcome is pending")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertTrue(thrown.getMessage().contains("asset export outcome remains unresolved")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -764,28 +957,23 @@ void uncertainAssetExportRemainsPendingForExactRetry() { @Test void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); - when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenThrow(new IllegalStateException("stage commit outcome is unknown")); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(versionAssetArtifactService).stageExport("tenant-1", 10L, 1, workflowId); + assertTrue(thrown.getMessage().contains("asset export intent commit requires exact readback")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 1, request.publishWorkflowId()); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(versionAssetArtifactService, never()) .markExportedUnattested( @@ -800,7 +988,8 @@ void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class)); + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); verify(versionAssetArtifactService, never()) .markFailed( any(String.class), @@ -820,9 +1009,9 @@ void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() @Test void readbackWithArtifactButNoBundleRemainsPartial() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -836,9 +1025,6 @@ void readbackWithArtifactButNoBundleRemainsPartial() { null, LocalDateTime.now(), List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); @@ -846,9 +1032,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("incomplete")); verify(publishAttemptService, never()).executeFullVersionTransaction(any()); @@ -860,9 +1044,13 @@ void readbackWithArtifactButNoBundleRemainsPartial() { @Test void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + PublishAttempt attempt = fixture.attempt(); + Version version = fixture.version(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(2L); List participantDigests = participantDigests(); PublishedReleaseBundleDto bundle = publishedReleaseBundleDto( @@ -892,19 +1080,21 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { null, LocalDateTime.now(), List.of("manifest.json")); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("manifest.json"), + artifactDigests(List.of("manifest.json")))); Game game = new Game(); game.setTenantId("tenant-1"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) @@ -916,25 +1106,21 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { .recordVerifiedDigests( "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); verify(publishAttemptService).markFullVersionSucceeded(workflowId); + verify(publishAttemptRepository).sealPublication(attempt, true); } @Test - void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - attempt.setId(101L); - attempt.setRequestDigest(null); + void selectedAttemptWithMismatchedVersionEvidenceIsNotRewritten() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); Version mismatchedVersion = fullVersion(10L, 2, VersionLifecycleState.DRAFT); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(mismatchedVersion)); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); verify(publishAttemptRepository, never()) .backfillFullVersionRequestDigestIfAbsent( @@ -944,26 +1130,19 @@ void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { any(Long.class), any(Integer.class), any(String.class)); - assertEquals(null, attempt.getRequestDigest()); + assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } @Test - void legacyFullMixedScopeAttemptIsNotRebound() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - attempt.setId(101L); - attempt.setRequestDigest(null); + void selectedFullAttemptWithMixedScopeIsNotRebound() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); attempt.setBaseVersionId(3L); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); verify(publishAttemptRepository, never()) .backfillFullVersionRequestDigestIfAbsent( @@ -973,22 +1152,19 @@ void legacyFullMixedScopeAttemptIsNotRebound() { any(Long.class), any(Integer.class), any(String.class)); - assertEquals(null, attempt.getRequestDigest()); + assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } @Test void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + PublishAttempt attempt = fixture.attempt(); attempt.setScriptPatchVersion("legacy-patch"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); verify(publishedReleaseBundleService, never()) @@ -996,91 +1172,27 @@ void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { } @Test - void nonCanonicalLegacyFullWorkflowFailsBeforeCompatibilityRewrite() { - PublishAttempt attempt = - fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, "legacy-random-workflow"); - attempt.setId(101L); - attempt.setRequestDigest(null); - - assertThrows( - IllegalArgumentException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest( - "tenant-1", "notes", "workflow-1", "legacy-random-workflow"))); - - verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - } - - @Test - void missingLegacyPublishRequestIdIsRecoveredFromCanonicalWorkflowId() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.FAILED, 10L, 1, workflowId); - attempt.setRequestDigest(null); - attempt.setFailureCode("PUBLISH_FAILED"); - attempt.setFailureMessage("legacy publish failure"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", null, workflowId)); - - assertEquals("FAILED", snapshot.status()); - assertEquals("PUBLISH_FAILED", snapshot.failureCode()); - verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); - } - - @Test - void missingLegacyPublishRequestIdDoesNotCrossTenantWorkflowPrefix() { - String workflowId = "publish:tenant-2:publish-request:workflow-1"; - - assertThrows( - IllegalArgumentException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", null, workflowId))); - - verify(publishAttemptRepository, never()).findByPublishWorkflowId(any(String.class)); - } - - @Test - void mismatchedRequestDigestCannotReplaySucceededAttempt() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); - attempt.setRequestDigest("0".repeat(64)); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - - verify(publishedReleaseBundleService, never()) - .findPublishedReleaseBundle(any(String.class), any(Long.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - - @Test - void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - Game game = new Game(); - game.setTenantId("tenant-1"); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + void postBundleFailureAfterRollbackLeavesAttemptPendingWithoutCleaningAssets() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + Version version = fixture.version(); + String workflowId = request.publishWorkflowId(); List participantDigests = participantDigests(); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto staged = stagedArtifact(request, version); + VersionAssetArtifactStateDto exportedState = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); PublishedReleaseBundleDto bundle = publishedReleaseBundleDto( 1L, @@ -1096,9 +1208,11 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { false, null, LocalDateTime.now()); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests); @@ -1129,11 +1243,11 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + same(capturedWorldPublicationEvidence))) .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); org.mockito.Mockito.doAnswer( invocation -> { // The production transaction rolls managed entity changes back before readback. @@ -1144,29 +1258,34 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .when(versionRepository) .save(any(Version.class)); - PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertEquals("FAILED", snapshot.status()); - verify(publishAttemptService) + assertTrue(thrown.getMessage().contains("incomplete evidence")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } @Test void finalizationFailureWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); @@ -1182,15 +1301,13 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); assertEquals(1, readFailure.getSuppressed().length); assertEquals(operationFailure, readFailure.getSuppressed()[0]); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1198,63 +1315,32 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @ParameterizedTest - @EnumSource( - value = Status.Code.class, - names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) - void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); - - IllegalStateException thrown = - assertThrows( - IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); - - assertTrue(thrown.getMessage().contains("temporarily unavailable")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - @Test void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); org.mockito.Mockito.doThrow(new IllegalStateException("commit outcome unknown")) .when(publishAttemptService) .executeFullVersionTransaction(any()); assertThrows( IllegalStateException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1264,15 +1350,17 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { @Test void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + String workflowId = request.publishWorkflowId(); + VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(staged)); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); @@ -1287,15 +1375,13 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("readback failed")); assertEquals(readFailure, thrown.getCause()); assertEquals(1, readFailure.getSuppressed().length); assertEquals(ambiguousCommit, readFailure.getSuppressed()[0]); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); @@ -1305,31 +1391,19 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { @Test void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() { - String workflowId = "publish:tenant-1:publish-request:workflow-1"; - PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); - Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - Game game = new Game(); - game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) - .thenReturn(Optional.of(attempt)); - when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests()); - when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); - when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) - .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); - java.util.concurrent.atomic.AtomicInteger transactionCalls = - new java.util.concurrent.atomic.AtomicInteger(); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, + "recorded digest mismatch")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); org.mockito.Mockito.doAnswer( invocation -> { - if (transactionCalls.getAndIncrement() == 0) { - throw new PublishAttemptService.FullVersionTransactionException( - new IllegalStateException("version finalization failed")); - } ((java.util.function.Supplier) invocation.getArgument(0)).get(); throw new IllegalStateException("failure-marking commit outcome unknown"); }) @@ -1339,14 +1413,17 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); - assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(publishAttemptService) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + .markFullVersionFailed( + request.publishWorkflowId(), + "RECORDED_CONTENT_DIGEST_MISMATCH", + "recorded digest mismatch"); + verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(assetExportService, never()) .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } @@ -1366,6 +1443,148 @@ private PublishAttempt fullAttempt( return attempt; } + private PublishIntent selectedIntent() { + return selectedReservation().selection().intent(); + } + + private SelectionSnapshot selectedReservation() { + UUID requestId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID commitId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-1", + List.of( + new RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "1"))); + PublishIntent intent = + new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "workflow-1", + "1", + "notes", + requestId, + commitId, + binding.digest()); + VisibilityFence fence = + new VisibilityFence( + target, + requestId, + commitId, + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(binding, fence)); + // This is an existing synchronized source selection fixture only. It carries no Account + // authorization or authenticated World publication freeze. + return new SelectionSnapshot(selection, OffsetDateTime.parse("2026-10-08T00:00:00Z")); + } + + private PublishWorkflowRequest selectedRequest(SelectionSnapshot reservation) { + PublishIntent intent = reservation.selection().intent(); + return new PublishWorkflowRequest( + "tenant-1", + intent.notes(), + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + intent); + } + + private PublishAttempt selectedAttempt( + SelectionSnapshot reservation, PublishWorkflowRequest request, int versionNumber) { + PublishAttempt attempt = + fullAttempt( + PublishAttemptStatus.PENDING, + reservation.selection().target().gameDesignVersionRowId(), + versionNumber, + request.publishWorkflowId()); + attempt.setRequestDigest(reservation.selection().digest()); + return attempt; + } + + private SelectedPublishFixture selectedPublishFixture(int versionNumber) { + SelectionSnapshot reservation = selectedReservation(); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = selectedAttempt(reservation, request, versionNumber); + Version version = fullVersion(10L, versionNumber, VersionLifecycleState.DRAFT); + version.setNotes("notes"); + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(publishAttemptRepository.findByPublishWorkflowIdForUpdate(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 10L)) + .thenReturn(Optional.of(version)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + return new SelectedPublishFixture(reservation, request, attempt, version); + } + + private VersionAssetArtifactStateDto stagedArtifact( + PublishWorkflowRequest request, Version version) { + return new VersionAssetArtifactStateDto( + "tenant-1", + version.getId(), + version.getVersionNumber(), + "STAGED", + 1L, + null, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of()); + } + + private PublishWorkflowSnapshot reflectiveUnitHarnessReconcileSelectedPublicationMechanics( + PublishWorkflowRequest request) { + try { + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileSelectedPublicationMechanics", PublishWorkflowRequest.class); + mechanics.setAccessible(true); + return (PublishWorkflowSnapshot) mechanics.invoke(service, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) throw runtimeException; + if (cause instanceof Error error) throw error; + throw new AssertionError("selected publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("selected publication mechanics harness is unavailable", exception); + } + } + private Version fullVersion(long versionId, int versionNumber, VersionLifecycleState state) { Version version = new Version(); version.setId(versionId); @@ -1380,9 +1599,21 @@ private Version fullVersion(long versionId, int versionNumber, VersionLifecycleS private List participantDigests() { return List.of( new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest", 1, null, null)); + "GAME_DESIGN_CONTROL_PLANE", + "10", + selectedIntent().selectedCommitId().toString(), + "digest", + 1, + null, + null)); } + private record SelectedPublishFixture( + SelectionSnapshot reservation, + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version) {} + private static ExportedAssetManifest exportedManifest(List usageKeys) { return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 34bb6b3cbe..2fc21d08f1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -21,6 +21,7 @@ import java.util.function.Supplier; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PluginVersionStatusEventDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -92,6 +93,18 @@ class VersionServiceImplTest { private VersionServiceImpl service; + private static PublishIntent selectedIntent() { + return new PublishIntent( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISH_REQUEST_ID, + "1", + "notes", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "a".repeat(64)); + } + @BeforeEach void setup() throws Exception { MockitoAnnotations.openMocks(this); @@ -131,39 +144,58 @@ void setup() throws Exception { } @Test - void publishVersionUsesTenantScopedVersionSequence() throws Exception { + void publishVersionRequiresCurrentAuthorizationAndOwnerFreeze() { + IllegalStateException thrown = + assertThrows(IllegalStateException.class, () -> service.publishVersion(selectedIntent())); + + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")); + verify(publishCommandService, org.mockito.Mockito.never()).reserveSelection(any()); + verify(publishCommandService, org.mockito.Mockito.never()) + .publishFullVersion( + any(String.class), any(String.class), any(String.class), any(String.class)); + org.mockito.Mockito.verifyNoInteractions(temporalPublishOrchestrator); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .assertGatePassed(any(VersionDto.class), any(List.class)); + } + + @Test + void legacyFullVersionRequestOnlyDelegatesToRetainedTerminalReplay() throws Exception { + VersionDto expected = + new VersionDto( + 10L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); when(publishCommandService.publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.eq( - "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID))) - .thenReturn( - new VersionDto( - 10L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now())); + "tenant-1", + "notes", + PUBLISH_REQUEST_ID, + "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)) + .thenReturn(expected); - VersionDto dto = service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + VersionDto actual = service.replayLegacyFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); + assertEquals(expected, actual); verify(publishCommandService) .publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.eq( - "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); + "tenant-1", + "notes", + PUBLISH_REQUEST_ID, + "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID); + org.mockito.Mockito.verifyNoInteractions(temporalPublishOrchestrator); } @Test @@ -851,27 +883,20 @@ private Version scriptPatchVersion( } @Test - void publishVersionPropagatesTypedPublishGateFailures() { - when(publishCommandService.publishFullVersion( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq("notes"), - org.mockito.ArgumentMatchers.eq(PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.anyString())) - .thenThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")); - - PublishGateFailureException thrown = + void publishVersionCannotReachPublishGatesWithoutOwnerFreeze() { + IllegalStateException thrown = org.junit.jupiter.api.Assertions.assertThrows( - PublishGateFailureException.class, - () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + IllegalStateException.class, () -> service.publishVersion(selectedIntent())); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")); + verify(publishGateService, org.mockito.Mockito.never()).assertGatePassed(any(), any()); + verify(publishCommandService, org.mockito.Mockito.never()) + .publishFullVersion( + any(String.class), any(String.class), any(String.class), any(String.class)); } @Test - void publishVersionDeletesExportedAssetsWhenAttestationWriteFails() { + void publishVersionDoesNotStartTemporalWorkflowWithoutOwnerFreeze() { VersionServiceImpl temporalService = new VersionServiceImpl( versionRepository, @@ -890,25 +915,20 @@ void publishVersionDeletesExportedAssetsWhenAttestationWriteFails() { pluginBundleStorageService, publishCommandService, Optional.of(temporalPublishOrchestrator)); - when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) - .thenReturn( - new VersionDto( - 10L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now())); - - VersionDto dto = temporalService.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> temporalService.publishVersion(selectedIntent())); - assertEquals(10L, dto.id()); - verify(temporalPublishOrchestrator).publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + assertTrue(thrown.getMessage().startsWith("PUBLICATION_AUTHORIZATION_UNAVAILABLE:")); + org.mockito.Mockito.verifyNoInteractions(temporalPublishOrchestrator); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + verify(publishGateService, org.mockito.Mockito.never()) + .assertGatePassed(any(VersionDto.class), any(List.class)); } @Test From c620701002ffe387d339a005f2e6a5a143149bd5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:08:39 +1300 Subject: [PATCH 06/29] Fix publication tracker table after foundation merge --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index e60c54b4bc..d9ede4da38 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -59,7 +59,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the source now includes Draft `version_asset` mappings, a durable version-scoped export snapshot, independent candidate readback, and immutable v1 bundle storage with canonical identity, an opaque reference, manifest schema, and artifact digests. This foundation has not been validated on the integrated branch; migration execution and focused database proof remain pending. Destructive lifecycle operations, global publication/purge fencing, exact-byte repair, complete creator asset UX, and runtime launch activation remain unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for revision/version metadata, fail-closed public and Temporal ingress, exact terminal replay, and conditional unit mechanics for selected source capture, staging/readback, finalization, sealing, and ambiguous outcomes. Reflection-based mechanics proof is not production authority or success proof. Historical revision/version lineage, post-bundle failure reconciliation, same-commit attestation convergence, complete digest/attestation tuples, and publication-bound generation remain unproved. The owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: fresh/PENDING requests are denied before mutation at public and registered Temporal ingress; selected mechanics remain harness-only conditional proof. Participant tokens are synthetic and World emits schema 2 while the gate accepts schema 1. Release storage now retains canonical Version identity/reference, manifest schema, artifact digests, exact readback, and selected World evidence on the v2 path, but target commit provenance and a public tenant projection remain absent. Accepted publication, release, asset, and procedural-generation decisions define the target authority chain; complete digest/attestation tuples and publication-bound generation remain incomplete. +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for revision/version metadata, fail-closed public and Temporal ingress, exact terminal replay, and conditional unit mechanics for selected source capture, staging/readback, finalization, sealing, and ambiguous outcomes. Reflection-based mechanics proof is not production authority or success proof. Historical revision/version lineage, post-bundle failure reconciliation, same-commit attestation convergence, complete digest/attestation tuples, and publication-bound generation remain unproved. The owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: fresh/PENDING requests are denied before mutation at public and registered Temporal ingress; selected mechanics remain harness-only conditional proof. Participant tokens are synthetic and World emits schema 2 while the gate accepts schema 1. Release storage now retains canonical Version identity/reference, manifest schema, artifact digests, exact readback, and selected World evidence on the v2 path, but target commit provenance and a public tenant projection remain absent. Accepted publication, release, asset, and procedural-generation decisions define the target authority chain; complete digest/attestation tuples and publication-bound generation remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | From db7a85455bac6e34490dc11bc05e2a9a5a223733 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:11:49 +1300 Subject: [PATCH 07/29] Align launch denial fixture with the private owner read --- .../service/LaunchDescriptorServiceIntegrationTest.java | 4 +--- .../service/impl/VersionPublishCommandServiceImplTest.java | 6 +++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 4f6f3d15e0..7765a74313 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -59,9 +59,7 @@ void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + " required to resolve a launch descriptor"); - assertThat( - launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "1", 9L, "integration-cp-unbound")) + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) .isEmpty(); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index b6d8b3feb8..6d67dfc5b0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -561,11 +561,11 @@ void selectedFailedReplayRequiresTheExactNoPublicationSeal() { assertEquals("FAILED", service.reconcileFullVersionPublish(request).status()); verify(publishAttemptRepository).requireNoPublicationOperation(attempt); - org.mockito.Mockito.doThrow(new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED")) + org.mockito.Mockito.doThrow( + new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED")) .when(publishAttemptRepository) .requireNoPublicationOperation(attempt); - assertThrows( - IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); + assertThrows(IllegalStateException.class, () -> service.reconcileFullVersionPublish(request)); verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); } From fa54369d5031519ab1f31abe809c08f4c637d89b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:57:49 +1300 Subject: [PATCH 08/29] test(game-design): clear selected fixture static-analysis failures --- .../PublishAttemptServiceTransactionIntegrationTest.java | 5 +---- .../service/impl/VersionPublishCommandServiceImplTest.java | 3 --- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 022c8d6f5a..5c1f4a98c1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -38,8 +38,6 @@ import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; -import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; -import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; @@ -657,8 +655,7 @@ private ExportedAssetManifest recordFixtureCandidate( versionAssetPublicationService.associateDraftAsset( tenantId, version.getId(), persistedAsset.getId(), "fixture.bin"); versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); - return exportCandidateService.recordExportCandidate( - tenantId, versionNumber, candidate); + return exportCandidateService.recordExportCandidate(tenantId, versionNumber, candidate); } private record SelectedPublicationFixture( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 80b9d59492..277666ac6b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -1072,7 +1072,6 @@ void readbackWithArtifactButNoBundleRemainsPartial() { @Test void selectedStagedArtifactWithMismatchedWorkflowRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); - PublishWorkflowRequest request = fixture.request(); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -1202,8 +1201,6 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { 1, List.of("manifest.json"), artifactDigests(List.of("manifest.json")))); - Game game = new Game(); - game.setTenantId("tenant-1"); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); From 32b87f207958a03dad7056926ce0a13a1547aef7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:14:26 +1300 Subject: [PATCH 09/29] test(game-design): bind source fixtures to transaction and migration contracts --- ...redWorldSourceDeliveryIntegrationTest.java | 2 +- ...emptServiceTransactionIntegrationTest.java | 92 +++++++++---------- 2 files changed, 46 insertions(+), 48 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java index 20d222fff3..1627764478 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -40,7 +40,7 @@ class GameAuthoredWorldSourceDeliveryIntegrationTest { private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; private static final String NAMESPACE = "authored-world-delivery-test"; - private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("40"); + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("39"); private static final Table GAME = DSL.table(DSL.name("game")); private static final Table SOURCE_OPERATIONS = DSL.table(DSL.name("game_design_authored_world_source_operations")); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 5c1f4a98c1..f7e916c379 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -56,6 +56,7 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -537,53 +538,50 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { /** Fixture-only Account/World inputs; this exercises GD's actual selected owner transaction. */ private SelectedPublicationFixture selectedPublicationFixture( String tenantId, String gameName, boolean includePublishedSource) { - return new TransactionTemplate(transactionManager) - .execute( - status -> { - Game game = new Game(); - game.setTenantId(tenantId); - game.setName(gameName); - gameRepository.save(game); - - if (includePublishedSource) { - Version source = new Version(); - source.setTenantId(tenantId); - source.setVersionNumber(1); - source.setVersionState(VersionLifecycleState.PUBLISHED); - source.setVersionStateEpoch(2L); - source.setNotes("ISOLATED remap source"); - versionRepository.save(source); - } - - Version draft = new Version(); - draft.setTenantId(tenantId); - draft.setVersionNumber(includePublishedSource ? 2 : 1); - draft.setVersionState(VersionLifecycleState.DRAFT); - draft.setVersionStateEpoch(1L); - draft.setNotes("ISOLATED selected publication"); - Version persisted = versionRepository.save(draft); - TargetProof target = - new TargetProof( - persisted.getCanonicalTenantId(), - persisted.getCanonicalVersionId(), - persisted.getId(), - persisted.getTenantId(), - persisted.getIdentitySourceGameRowId(), - persisted.getIdentitySourceGameTenantKey(), - persisted.getIdentitySourceProvenanceKind()); - try { - GameDesignPublicationOperation operation = - IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( - dsl, - target, - persisted.getVersionStateEpoch(), - "ISOLATED publication proof"); - return new SelectedPublicationFixture(persisted, operation); - } catch (Exception failure) { - throw new IllegalStateException( - "Selected publication fixture setup failed", failure); - } - }); + TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager); + sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return sourceTransaction.execute( + status -> { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName(gameName); + gameRepository.save(game); + + if (includePublishedSource) { + Version source = new Version(); + source.setTenantId(tenantId); + source.setVersionNumber(1); + source.setVersionState(VersionLifecycleState.PUBLISHED); + source.setVersionStateEpoch(2L); + source.setNotes("ISOLATED remap source"); + versionRepository.save(source); + } + + Version draft = new Version(); + draft.setTenantId(tenantId); + draft.setVersionNumber(includePublishedSource ? 2 : 1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("ISOLATED selected publication"); + Version persisted = versionRepository.save(draft); + TargetProof target = + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind()); + try { + GameDesignPublicationOperation operation = + IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, target, persisted.getVersionStateEpoch(), "ISOLATED publication proof"); + return new SelectedPublicationFixture(persisted, operation); + } catch (Exception failure) { + throw new IllegalStateException("Selected publication fixture setup failed", failure); + } + }); } private Object reconcileSelectedPublicationMechanics(SelectedPublicationFixture fixture) { From 5fe03e2f477e06835bc3bddb8a8148e4b22b4834 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:00:41 +1300 Subject: [PATCH 10/29] docs: clarify authorized read bindings and fail-closed version CAS --- .../microservices/game-design-service/version-control.md | 4 ++++ design/architecture/system-architecture-versioning-runtime.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 4e66192881..dec915b7c4 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -136,6 +136,10 @@ Game Logic's owner-local full-version manifest and provenance remain unproved. I Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. +For launch, attestation, and source-operation reads, workload authentication and request scope are necessary but not sufficient authorization. The read must also be bound to an authenticated, immutable receipt issued by the independently authorized owning operation: the receipt identifies the certificate-derived caller workload and namespace, canonical tenant, exact version and selected commit/digest, read purpose and scope, and the governing authorized operation/lifecycle. Caller-supplied tenant, correlation, or workload fields alone confer no authority. A valid receipt for an exact terminal read does not require that the version still have an active Draft. The binding preserves existing Account authorization and owner-source checks required by their contracts; exact terminal reads remain subject to the documented terminal-read policy and do not derive perpetual authority from a retained receipt. Operator diagnostics remain separately Account-authorized and do not gain launch or mutation authority through this binding. The receipt is evidence of the owning operation's existing authority, not a new revocation authority; this contract does not define a new receipt expiry or lifetime. + +**Current implementation gap:** the three existing legacy reads (`GetPublishedReleaseBundle`, `GetVersionState`, and `GetVersionAssetArtifactState`) still rely on generic-internal or exact-workload checks without this owner-verifiable read-scope binding. The authenticated receipt producer handoff from each independently authorized owning operation remains open; until that evidence is supplied and verified, these reads do not satisfy the target authorization contract. + In addition to domain-service digests, publish safety requires a Game Design control-plane digest: - Game Design computes a canonical digest over normalized dependency rows that affect launchability and publish immutability (for example `game_template_*_ref`, `version_asset`, and related version wiring metadata). diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index b14e4f8fd0..f4e099b139 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -24,7 +24,7 @@ The failed-candidate purge exception is target-only as well: Game Design must du The destructive asset lifecycle also remains target-only for operation durability: `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` must share the ADR 0048 owner-local operation envelope and result ledger (caller-stable operation/workflow identity, canonical `mutationDigest/v1`, exact replay, and `IDEMPOTENCY_CONFLICT` for changed input). The current first slice has no such shared ledger/digest contract, and `BeginPurgeVersionAssets` still mints a random workflow identity server-side. In addition, both artifact and Version lifecycle saves lack database epoch predicates and affected-row CAS proof, so `expectedVersionStateEpoch` cannot yet establish durable abandonment/retirement invalidation. -The live `CompareAndSetVersionState` path has a separate transition-safety gap: it checks the expected epoch in service memory but accepts any non-null lifecycle enum and saves it without enforcing legal transitions, requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or applying retirement predicates for active instances, templates, and in-flight activation. It must not be treated as an activation- or retirement-safe authority until those guards and focused proof exist. +The live `CompareAndSetVersionState` path enforces tenant/version lookup and expected-epoch validation, returns an exact same-state no-op, and denies every state-changing request before Version writes. This fail-closed boundary does not complete the [Game Design owner transition contract](./microservices/game-design-service/api-contracts.md#grpc-apis), database epoch-CAS/affected-row proof, or activation and retirement proof; state-changing transitions remain unavailable, and the API is not an activation- or retirement-safe authority. Post-bundle publish failure is likewise unresolved: target reconciliation must read back whether `published_release_bundle` committed and must never delete Version as compensation. The current catch path still attempts that delete; the bundle's non-cascading foreign key can make it fail after commit. Focused proof must cover committed-bundle, absent-bundle, and ambiguous readback outcomes. From e764f85ebafbd328d0706077643e14279cb301d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:09:13 +1300 Subject: [PATCH 11/29] test(game-design): bind publish transaction fixtures to complete owner evidence --- ...emptServiceTransactionIntegrationTest.java | 38 +++---------------- 1 file changed, 5 insertions(+), 33 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 422f1f364a..be0e502429 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -18,7 +18,6 @@ import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; -import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; @@ -41,6 +40,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; @@ -259,22 +259,8 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { .thenAnswer( invocation -> { VersionDto version = invocation.getArgument(0); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(version.id()), - fixture - .operation() - .account() - .input() - .selection() - .selectedCommit() - .commitId() - .toString(), - "transaction-proof-design-digest", - 1, - null, - null)); + return PublishedWorldSelectorFixtures.participants( + version.id(), fixture.operation().world()); }); Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) .thenAnswer(invocation -> recordFixtureCandidate(fixture)); @@ -335,22 +321,8 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { VersionDto candidate = invocation.getArgument(0); candidateVersionId.set(candidate.id()); candidateVersionNumber.set(candidate.versionNumber()); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(candidate.id()), - fixture - .operation() - .account() - .input() - .selection() - .selectedCommit() - .commitId() - .toString(), - "failed-remap-design-digest", - 1, - null, - null)); + return PublishedWorldSelectorFixtures.participants( + candidate.id(), fixture.operation().world()); }); Mockito.doAnswer( invocation -> { From 887f5728718c40f25504f4c99b681bbd7f2b7d14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:09:14 +1300 Subject: [PATCH 12/29] feat(common): define bounded StartSession operator action digest contract --- .../start-session-action-schema.md | 48 ++ .../tests/test_start_session_action_digest.py | 311 +++++++++ .../common/operator/MutationDigestV1.java | 299 +++++++++ .../operator/StartSessionOperatorAction.java | 143 +++++ .../StartSessionOperatorActionCodec.java | 605 ++++++++++++++++++ .../StartSessionOperatorActionCodecTest.java | 225 +++++++ ...rt-session-mutation-digest-v1-vectors.json | 167 +++++ 7 files changed, 1798 insertions(+) create mode 100644 design/architecture/microservices/game-session-service/start-session-action-schema.md create mode 100644 dev-tools/tests/test_start_session_action_digest.py create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java create mode 100644 services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md new file mode 100644 index 0000000000..b3b3432495 --- /dev/null +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -0,0 +1,48 @@ +# StartSession Operator Action Schema + +## Normative contract + +This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. + +The request is a JSON object whose declared member order is `actionFamilySchemaId`, `actionFamilySchemaVersion`, `scope`, `target`, `expectedVersion`, `mutation`, and `auditReason`. `expectedVersion` is absent for this creation action and must not appear in the JSON request, including as `null`. Its absence remains an explicit seventh field in the canonical digest preimage. All other top-level members are required. + +| Member | Required shape and constraint | +| --- | --- | +| `actionFamilySchemaId` | String exactly `firemud.game-session.start-session`. | +| `actionFamilySchemaVersion` | String exactly `1`. | +| `scope` | Object with exactly `tenantId`, then `targetNamespace`. | +| `scope.tenantId` | Canonical lowercase, hyphenated, non-nil UUID. | +| `scope.targetNamespace` | Kubernetes workload namespace label: 1–63 lowercase ASCII letters or digits, with internal hyphens allowed and no leading or trailing hyphen. | +| `target` | Object with exactly `gameTemplateId`, then `ownerAccountId`. | +| `target.gameTemplateId` | JSON string matching `[1-9][0-9]*`, within the current owner's signed `long` range. JSON numbers and strings with a sign, leading zero, decimal point, or exponent are rejected. | +| `target.ownerAccountId` | Canonical lowercase, hyphenated, non-nil Account UUID. Private legacy identifier mappings remain the receiver's responsibility. | +| `expectedVersion` | Explicitly absent for StartSession creation. Any supplied value, including `null`, is rejected. | +| `mutation` | Object with the optional member `clientIp`. | +| `mutation.clientIp` | Absent or a string whose NFC-normalized UTF-8 encoding is at most 128 bytes. Empty string is distinct from absence. `null` and all other types are rejected. No address parsing or ownership claim is implied. | +| `auditReason` | Required string, nonblank after NFC normalization, at most 1,000 normalized UTF-8 bytes. | + +JSON object members must appear in the declared order. Duplicate raw keys, keys colliding after NFC normalization, unknown or missing members, wrong JSON types, malformed Unicode, invalid UTF-8, and trailing tokens are rejected before a digest is returned. Object and array values use the recursive typed grammar from [ADR 0047, Bounded Owner Delegation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation); no generic JSON canonicalization is a substitute. + +The schema uses these shared parser and encoding bounds: + +| Limit | Maximum | +| --- | ---: | +| Raw UTF-8 JSON input | 16 KiB | +| Composite nesting depth | 8 | +| Members in one object | 16 | +| Elements in one array | 64 | +| NFC-normalized string or object-key bytes | 4,096 | +| Raw or canonical numeric bytes | 128 | +| Numeric scale | 128 | +| Canonical segment payload | 8,192 bytes | +| Complete `mutationDigest/v1` preimage | 32 KiB | + +## Digest inputs and exclusions + +The SHA-256 preimage follows ADR 0047's exact `mutationDigest/v1` framing. The schema pair and these typed fields are included in the ADR-defined order: `scope`, `target`, absent `expectedVersion`, `mutation`, and `auditReason`. The `mutation` object always declares one member, `clientIp`; if it is omitted from JSON, the digest still includes that member in its declared position with type `absent` and presence `0`. An empty string is encoded as a present `string` and therefore has a different digest. + +The target owner is fixed to `game-session-service` for this schema and is carried separately in the ADR 0048 execution tuple; it is not a digest field. `controlPlaneRequestId`, any separately tagged action-family request identity, reservation owner and claim fence, transport credentials, opaque authorization references, actor assertions, and Account authority evidence are outside these seven grammar fields and are compared at their respective boundaries under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md#one-correlated-execution). + +The action contains no runtime version or patch input. It does not assert current ownership or authority. Game Design selects a launch descriptor under its independently authorized operation; the Game Session owner performs its separate domain and execution checks. + +The shared Java implementation exposes `StartSessionOperatorActionCodec.decode(byte[])`, `canonicalPreimage(...)`, and `mutationDigest(...)`, plus the immutable typed action accessors. Shared Java and Python conformance vectors are stored in [the common vector fixture](../../../../services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json). diff --git a/dev-tools/tests/test_start_session_action_digest.py b/dev-tools/tests/test_start_session_action_digest.py new file mode 100644 index 0000000000..93a94b9a2e --- /dev/null +++ b/dev-tools/tests/test_start_session_action_digest.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Standard-library conformance checks for StartSession mutationDigest/v1 vectors.""" + +import hashlib +import json +import re +import unicodedata +import unittest +from dataclasses import dataclass +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ( + ROOT + / "services/common-platform-core/src/test/resources/operator/" + / "start-session-mutation-digest-v1-vectors.json" +) +SCHEMA_ID = "firemud.game-session.start-session" +SCHEMA_VERSION = "1" +TOP_LEVEL_ORDER = [ + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason", +] +UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z") +NAMESPACE_PATTERN = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") +NUMBER_SOURCE = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\Z") +NUMBER_CANONICAL = re.compile(r"0|-?(?:[1-9][0-9]*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])\Z") + + +@dataclass(frozen=True) +class RawNumber: + lexeme: str + + +@dataclass(frozen=True) +class RawObject: + members: list + + +def reject_constant(_value): + raise ValueError("non-finite numeric value") + + +def parse_json(raw): + if len(raw) > 16 * 1_024: + raise ValueError("raw JSON exceeds its byte limit") + source = raw.decode("utf-8", "strict") + return json.loads( + source, + parse_int=RawNumber, + parse_float=RawNumber, + parse_constant=reject_constant, + object_pairs_hook=lambda pairs: RawObject(pairs), + ) + + +def scalar_string(value, byte_limit=4_096): + if not isinstance(value, str): + raise ValueError("string value required") + if any(0xD800 <= ord(character) <= 0xDFFF for character in value): + raise ValueError("malformed Unicode") + normalized = unicodedata.normalize("NFC", value) + encoded = normalized.encode("utf-8", "strict") + if len(encoded) > byte_limit: + raise ValueError("normalized string exceeds its byte limit") + return normalized + + +def segment(payload): + if len(payload) > 8_192: + raise ValueError("segment exceeds its byte limit") + return str(len(payload)).encode("ascii") + b":" + payload + + +def decimal_value(raw): + lexeme = raw.lexeme + encoded = lexeme.encode("ascii", "strict") + if len(encoded) > 128 or not NUMBER_SOURCE.fullmatch(lexeme): + raise ValueError("numeric source is invalid or too long") + fraction = lexeme.partition(".")[2] + if len(fraction) > 128: + raise ValueError("numeric scale exceeds its limit") + negative = lexeme.startswith("-") + unsigned = lexeme[1:] if negative else lexeme + integer, separator, fraction = unsigned.partition(".") + fraction = fraction.rstrip("0") if separator else "" + nonzero = any(digit != "0" for digit in integer + fraction) + if not nonzero: + canonical = "0" + elif fraction: + canonical = ("-" if negative else "") + integer + "." + fraction + else: + canonical = ("-" if negative else "") + integer + canonical_bytes = canonical.encode("ascii") + if len(canonical_bytes) > 128 or not NUMBER_CANONICAL.fullmatch(canonical): + raise ValueError("canonical number exceeds its limit") + return canonical_bytes + + +def encoded_value(value, depth=0): + if depth > 8: + raise ValueError("composite nesting is too deep") + if value is ABSENT: + return segment(b"absent") + b"0" + segment(b"") + if value is None: + return segment(b"null") + b"1" + segment(b"") + if isinstance(value, str): + payload = scalar_string(value).encode("utf-8") + return segment(b"string") + b"1" + segment(payload) + if isinstance(value, RawNumber): + return segment(b"number") + b"1" + segment(decimal_value(value)) + if isinstance(value, bool): + return segment(b"boolean") + b"1" + segment(b"true" if value else b"false") + if isinstance(value, RawObject): + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + normalized_members = [] + seen = set() + for raw_key, member_value in value.members: + key = scalar_string(raw_key).encode("utf-8") + if key in seen: + raise ValueError("duplicate or normalized-colliding object key") + seen.add(key) + normalized_members.append((key, member_value)) + payload = segment(str(len(normalized_members)).encode("ascii")) + for key, member_value in normalized_members: + payload += segment(key) + encoded_value(member_value, depth + 1) + return segment(b"object") + b"1" + segment(payload) + if isinstance(value, list): + if len(value) > 64: + raise ValueError("array exceeds its element limit") + payload = segment(str(len(value)).encode("ascii")) + for item in value: + payload += encoded_value(item, depth + 1) + return segment(b"array") + b"1" + segment(payload) + raise ValueError("unsupported typed JSON value") + + +ABSENT = object() + + +def ordered_members(value, declared_order, optional=()): + if not isinstance(value, RawObject): + raise ValueError("object value required") + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + members = {} + actual_order = [] + for raw_key, member_value in value.members: + key = scalar_string(raw_key) + if key in members: + raise ValueError("duplicate or normalized-colliding object key") + members[key] = member_value + actual_order.append(key) + if any(key not in declared_order for key in actual_order): + raise ValueError("unknown object member") + expected_order = [key for key in declared_order if key in members or key not in optional] + if actual_order != expected_order: + raise ValueError("missing or out-of-order object member") + return members + + +def canonical_uuid(value, label): + normalized = scalar_string(value) + if not UUID_PATTERN.fullmatch(normalized) or normalized == "00000000-0000-0000-0000-000000000000": + raise ValueError(f"{label} is not a canonical non-nil UUID") + return normalized + + +def action_preimage(raw): + root = parse_json(raw) + members = ordered_members(root, TOP_LEVEL_ORDER, optional={"expectedVersion"}) + if members.get("actionFamilySchemaId") != SCHEMA_ID: + raise ValueError("wrong schema id") + if members.get("actionFamilySchemaVersion") != SCHEMA_VERSION: + raise ValueError("wrong schema version") + if "expectedVersion" in members: + raise ValueError("expectedVersion must be absent") + + scope = ordered_members(members["scope"], ["tenantId", "targetNamespace"]) + tenant_id = canonical_uuid(scope["tenantId"], "tenantId") + namespace = scalar_string(scope["targetNamespace"]) + if len(namespace) > 63 or not NAMESPACE_PATTERN.fullmatch(namespace): + raise ValueError("invalid workload namespace") + + target = ordered_members(members["target"], ["gameTemplateId", "ownerAccountId"]) + template_id = scalar_string(target["gameTemplateId"]) + if not re.fullmatch(r"[1-9][0-9]*", template_id): + raise ValueError("gameTemplateId must be a positive canonical decimal string") + if len(template_id) > 19 or ( + len(template_id) == 19 and template_id > "9223372036854775807" + ): + raise ValueError("gameTemplateId exceeds the current owner long range") + owner_id = canonical_uuid(target["ownerAccountId"], "ownerAccountId") + + mutation = ordered_members(members["mutation"], ["clientIp"], optional={"clientIp"}) + if "clientIp" not in mutation: + client_ip = ABSENT + else: + client_ip = mutation["clientIp"] + if not isinstance(client_ip, str): + raise ValueError("clientIp must be an absent or string value") + client_ip = scalar_string(client_ip, 128) + + audit_reason = scalar_string(members["auditReason"], 1_000) + if not audit_reason or all(character.isspace() for character in audit_reason): + raise ValueError("auditReason must not be blank") + + values = [ + ("actionFamilySchemaId", SCHEMA_ID), + ("actionFamilySchemaVersion", SCHEMA_VERSION), + ( + "scope", + RawObject( + [ + ("tenantId", tenant_id), + ("targetNamespace", namespace), + ] + ), + ), + ( + "target", + RawObject( + [ + ("gameTemplateId", template_id), + ("ownerAccountId", owner_id), + ] + ), + ), + ("expectedVersion", ABSENT), + ("mutation", RawObject([("clientIp", client_ip)])), + ("auditReason", audit_reason), + ] + result = segment(b"mutationDigest/v1") + for name, typed_value in values: + result += segment(name.encode("utf-8")) + encoded_value(typed_value) + if len(result) > 32 * 1_024: + raise ValueError("preimage exceeds its byte limit") + return result + + +def raw_vector_bytes(vector): + if "rawHex" in vector: + return bytes.fromhex(vector["rawHex"]) + return vector["input"].encode("utf-8", "strict") + + +class StartSessionMutationDigestVectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.fixture = json.loads(FIXTURE.read_text(encoding="utf-8")) + + def test_action_vectors(self): + results = {} + for vector in self.fixture["vectors"]: + with self.subTest(vector=vector["name"]): + raw = raw_vector_bytes(vector) + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + action_preimage(raw) + continue + preimage = action_preimage(raw) + digest = hashlib.sha256(preimage).hexdigest() + self.assertEqual(preimage.hex(), vector["preimageHex"]) + self.assertEqual(digest, vector["digest"]) + results[vector["name"]] = digest + + self.assertNotEqual(results["base"], results["changed-target"]) + self.assertNotEqual(results["base"], results["changed-scope"]) + self.assertNotEqual(results["base"], results["changed-audit-reason"]) + self.assertNotEqual(results["client-ip-absent"], results["client-ip-empty"]) + self.assertEqual(results["unicode-composed"], results["unicode-decomposed"]) + + def test_generic_value_grammar_vectors(self): + encodings = {} + for vector in self.fixture["grammarVectors"]: + with self.subTest(vector=vector["name"]): + if vector["kind"] == "numberLexeme": + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError)): + encoded_value(RawNumber(vector["rawLexeme"])) + continue + canonical = encoded_value(RawNumber(vector["rawLexeme"])) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + continue + if vector["kind"] == "reject": + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + continue + if vector["kind"] == "absent": + canonical = encoded_value(ABSENT) + else: + canonical = encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + + self.assertNotEqual(encodings["absent"], encodings["null"]) + self.assertNotEqual(encodings["number-one"], encodings["string-one"]) + self.assertEqual(encodings["number-signed-zero"], encodings["number-zero"]) + self.assertEqual(encodings["unicode-key-composed"], encodings["unicode-key-decomposed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java new file mode 100644 index 0000000000..1da36c7cbe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.common.operator; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Package-private implementation of the ADR 0047 mutationDigest/v1 byte grammar. */ +final class MutationDigestV1 { + static final int MAX_NORMALIZED_STRING_BYTES = 4_096; + static final int MAX_NUMERIC_BYTES = 128; + static final int MAX_NUMERIC_SCALE = 128; + static final int MAX_SEGMENT_BYTES = 8_192; + static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + + private static final String DOMAIN = "mutationDigest/v1"; + private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); + private static final Pattern NUMBER_CANONICAL = + Pattern.compile("0|-?(?:[1-9][0-9]*(?:\\.[0-9]*[1-9])?|0\\.[0-9]*[1-9])"); + + private MutationDigestV1() {} + + static byte[] preimage(StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(DOMAIN)); + writeField(output, "actionFamilySchemaId", string(action.actionFamilySchemaId())); + writeField(output, "actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())); + writeField( + output, + "scope", + object( + List.of( + member("tenantId", string(action.scope().tenantId().toString())), + member("targetNamespace", string(action.scope().targetNamespace()))))); + writeField( + output, + "target", + object( + List.of( + member("gameTemplateId", string(Long.toString(action.target().gameTemplateId()))), + member("ownerAccountId", string(action.target().ownerAccountId().toString()))))); + writeField(output, "expectedVersion", absent()); + Value clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? absent() + : string( + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + writeField(output, "mutation", object(List.of(member("clientIp", clientIp)))); + writeField(output, "auditReason", string(action.auditReason())); + byte[] preimage = output.toByteArray(); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + return preimage; + } + + static String sha256Hex(byte[] preimage) { + Objects.requireNonNull(preimage, "preimage is required"); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte value : digest) { + hex.append(Character.forDigit((value >>> 4) & 0x0f, 16)); + hex.append(Character.forDigit(value & 0x0f, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + static Value absent() { + return new ScalarValue("absent", false, new byte[0]); + } + + static Value nullValue() { + return new ScalarValue("null", true, new byte[0]); + } + + static Value string(String value) { + String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return new ScalarValue("string", true, utf8(normalized)); + } + + static Value number(String rawLexeme) { + Objects.requireNonNull(rawLexeme, "number lexeme is required"); + byte[] rawBytes = utf8(rawLexeme); + if (rawBytes.length > MAX_NUMERIC_BYTES || !NUMBER_SOURCE.matcher(rawLexeme).matches()) { + throw invalid("number lexeme is invalid or exceeds its byte limit"); + } + int decimalPoint = rawLexeme.indexOf('.'); + if (decimalPoint >= 0 && rawLexeme.length() - decimalPoint - 1 > MAX_NUMERIC_SCALE) { + throw invalid("number scale exceeds its limit"); + } + BigDecimal decimal; + try { + decimal = new BigDecimal(rawLexeme); + } catch (NumberFormatException exception) { + throw invalid("number lexeme is invalid"); + } + String canonical = decimal.signum() == 0 ? "0" : decimal.stripTrailingZeros().toPlainString(); + byte[] canonicalBytes = utf8(canonical); + if (canonicalBytes.length > MAX_NUMERIC_BYTES + || !NUMBER_CANONICAL.matcher(canonical).matches()) { + throw invalid("canonical number exceeds its byte limit"); + } + return new ScalarValue("number", true, canonicalBytes); + } + + static Value bool(boolean value) { + return new ScalarValue("boolean", true, utf8(value ? "true" : "false")); + } + + static Value object(List members) { + return new ObjectValue(members); + } + + static Value array(List values) { + return new ArrayValue(values); + } + + static Member member(String key, Value value) { + return new Member(key, value); + } + + static byte[] encodedValue(Value value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeValue(output, value); + return output.toByteArray(); + } + + static Value normalizeObject(List rawMembers) { + Objects.requireNonNull(rawMembers, "object members are required"); + if (rawMembers.size() > 16) { + throw invalid("object exceeds its member limit"); + } + List normalizedMembers = new ArrayList<>(rawMembers.size()); + List seenKeys = new ArrayList<>(rawMembers.size()); + for (Member member : rawMembers) { + String key = normalize(member.key(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (seenKeys.contains(key)) { + throw invalid("object contains a duplicate or normalized-colliding key"); + } + seenKeys.add(key); + normalizedMembers.add(new Member(key, member.value())); + } + return new ObjectValue(normalizedMembers); + } + + private static void writeField(ByteArrayOutputStream output, String name, Value value) { + writeSegment(output, utf8(name)); + writeValue(output, value); + if (output.size() > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + } + + private static void writeValue(ByteArrayOutputStream output, Value value) { + Objects.requireNonNull(value, "typed value is required"); + String type; + boolean present; + byte[] payload; + if (value instanceof ScalarValue scalar) { + type = scalar.type(); + present = scalar.present(); + payload = scalar.payload(); + } else if (value instanceof ObjectValue object) { + type = "object"; + present = true; + payload = objectPayload(object.members()); + } else if (value instanceof ArrayValue array) { + type = "array"; + present = true; + payload = arrayPayload(array.values()); + } else { + throw invalid("unsupported typed value"); + } + writeSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeSegment(output, payload); + } + + private static byte[] objectPayload(List members) { + if (members.size() > 16) { + throw invalid("object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeSegment(output, utf8(member.key())); + writeValue(output, member.value()); + } + return boundedPayload(output); + } + + private static byte[] arrayPayload(List values) { + if (values.size() > 64) { + throw invalid("array exceeds its element limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(values.size()))); + for (Value value : values) { + writeValue(output, value); + } + return boundedPayload(output); + } + + private static byte[] boundedPayload(ByteArrayOutputStream output) { + if (output.size() > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + return output.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String normalize(String value, int byteLimit, String label) { + Objects.requireNonNull(value, label + " is required"); + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8(normalized).length > byteLimit) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String label) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " contains malformed Unicode"); + } + } + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + sealed interface Value permits ScalarValue, ObjectValue, ArrayValue {} + + record ScalarValue(String type, boolean present, byte[] payload) implements Value { + ScalarValue { + Objects.requireNonNull(type); + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + record Member(String key, Value value) { + Member { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + } + } + + record ObjectValue(List members) implements Value { + ObjectValue { + members = List.copyOf(members); + } + } + + record ArrayValue(List values) implements Value { + ArrayValue { + values = List.copyOf(values); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java new file mode 100644 index 0000000000..59a09e72da --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable typed action covered by the StartSession operator schema. */ +public record StartSessionOperatorAction( + String actionFamilySchemaId, + String actionFamilySchemaVersion, + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + String auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.game-session.start-session"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "StartSession"; + public static final String OWNER_SERVICE = "game-session-service"; + + private static final Pattern WORKLOAD_NAMESPACE = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public StartSessionOperatorAction { + if (!ACTION_FAMILY_SCHEMA_ID.equals(actionFamilySchemaId)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaId"); + } + if (!ACTION_FAMILY_SCHEMA_VERSION.equals(actionFamilySchemaVersion)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaVersion"); + } + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + if (expectedVersion != ExpectedVersion.ABSENT) { + throw new IllegalArgumentException( + "expectedVersion must be absent for StartSession creation"); + } + Objects.requireNonNull(mutation, "mutation is required"); + auditReason = normalizedString(auditReason, "auditReason", 1_000); + if (isUnicodeBlank(auditReason)) { + throw new IllegalArgumentException("auditReason must not be blank"); + } + } + + public enum ExpectedVersion { + ABSENT + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner, which is compared outside the digest tuple. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope(UUID tenantId, String targetNamespace) { + public Scope { + Objects.requireNonNull(tenantId, "tenantId is required"); + if (NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("tenantId must not be nil"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + if (targetNamespace.length() > 63 || !WORKLOAD_NAMESPACE.matcher(targetNamespace).matches()) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + } + } + + public record Target(long gameTemplateId, UUID ownerAccountId) { + public Target { + if (gameTemplateId <= 0) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + Objects.requireNonNull(ownerAccountId, "ownerAccountId is required"); + if (NIL_UUID.equals(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must not be nil"); + } + } + } + + public record Mutation(ClientIp clientIp) { + public Mutation { + Objects.requireNonNull(clientIp, "clientIp presence is required"); + } + } + + /** The action schema accepts either an absent clientIp member or a string value. */ + public sealed interface ClientIp permits AbsentClientIp, StringClientIp { + static ClientIp absent() { + return new AbsentClientIp(); + } + + static ClientIp of(String value) { + return new StringClientIp(value); + } + } + + public record AbsentClientIp() implements ClientIp {} + + public record StringClientIp(String value) implements ClientIp { + public StringClientIp { + value = normalizedString(value, "clientIp", 128); + } + } + + private static String normalizedString(String value, String fieldName, int byteLimit) { + Objects.requireNonNull(value, fieldName + " is required"); + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > byteLimit) { + throw new IllegalArgumentException(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + } + + private static boolean isUnicodeBlank(String value) { + return value + .codePoints() + .allMatch( + codePoint -> Character.isWhitespace(codePoint) || Character.isSpaceChar(codePoint)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java new file mode 100644 index 0000000000..ed4552f151 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.common.operator; + +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.text.Normalizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Strict token-preserving JSON codec and digest entry point for StartSession operator actions. */ +public final class StartSessionOperatorActionCodec { + public static final int MAX_RAW_BYTES = 16 * 1_024; + public static final int MAX_NESTING_DEPTH = 8; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_ARRAY_ELEMENTS = 64; + public static final int MAX_NORMALIZED_STRING_BYTES = + MutationDigestV1.MAX_NORMALIZED_STRING_BYTES; + public static final int MAX_NUMERIC_BYTES = MutationDigestV1.MAX_NUMERIC_BYTES; + public static final int MAX_NUMERIC_SCALE = MutationDigestV1.MAX_NUMERIC_SCALE; + public static final int MAX_SEGMENT_BYTES = MutationDigestV1.MAX_SEGMENT_BYTES; + public static final int MAX_PREIMAGE_BYTES = MutationDigestV1.MAX_PREIMAGE_BYTES; + + private static final Pattern UUID_PATTERN = + 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 List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + private StartSessionOperatorActionCodec() {} + + /** Decodes only the declared StartSession schema and rejects every unsupported shape. */ + public static StartSessionOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + if (!(root instanceof JsonObject object)) { + throw invalid("StartSession action must be a JSON object"); + } + Map members = + orderedMembers(object, TOP_LEVEL_FIELDS, Set.of("expectedVersion")); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported StartSession action-family schema pair"); + } + if (members.containsKey("expectedVersion")) { + throw invalid("expectedVersion must be absent for StartSession creation"); + } + StartSessionOperatorAction.Scope scope = readScope(members.get("scope")); + StartSessionOperatorAction.Target target = readTarget(members.get("target")); + StartSessionOperatorAction.Mutation mutation = readMutation(members.get("mutation")); + String auditReason = requiredString(members.get("auditReason"), "auditReason"); + return new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + mutation, + auditReason); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for one typed action. */ + public static byte[] canonicalPreimage(StartSessionOperatorAction action) { + return MutationDigestV1.preimage(Objects.requireNonNull(action, "action is required")); + } + + /** Decodes an action and returns its exact ADR 0047 mutationDigest/v1 preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 digest for one typed action. */ + public static String mutationDigest(StartSessionOperatorAction action) { + return MutationDigestV1.sha256Hex(canonicalPreimage(action)); + } + + /** Decodes an action and returns its lowercase hexadecimal SHA-256 digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + /* Test bridge for the recursive value grammar. It is not an action-schema decoder. */ + static byte[] canonicalGrammarValueForTest(byte[] rawJson) { + JsonValue parsed = new StrictJsonParser(rawJson).parseDocument(); + return MutationDigestV1.encodedValue(toGrammarValue(parsed)); + } + + static byte[] absentGrammarValueForTest() { + return MutationDigestV1.encodedValue(MutationDigestV1.absent()); + } + + static byte[] canonicalNumberLexemeForTest(String rawLexeme) { + return MutationDigestV1.encodedValue(MutationDigestV1.number(rawLexeme)); + } + + private static StartSessionOperatorAction.Scope readScope(JsonValue value) { + JsonObject object = requireObject(value, "scope"); + Map members = + orderedMembers(object, List.of("tenantId", "targetNamespace"), Set.of()); + UUID tenantId = canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + return new StartSessionOperatorAction.Scope(tenantId, namespace); + } + + private static StartSessionOperatorAction.Target readTarget(JsonValue value) { + JsonObject object = requireObject(value, "target"); + Map members = + orderedMembers(object, List.of("gameTemplateId", "ownerAccountId"), Set.of()); + JsonValue templateValue = members.get("gameTemplateId"); + if (!(templateValue instanceof JsonString templateIdValue)) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + String templateIdText = + normalizeString(templateIdValue.value(), MAX_NORMALIZED_STRING_BYTES, "gameTemplateId"); + if (!templateIdText.matches("[1-9][0-9]*")) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + long gameTemplateId; + try { + gameTemplateId = Long.parseLong(templateIdText); + } catch (NumberFormatException exception) { + throw invalid("gameTemplateId exceeds the current owner long range"); + } + UUID ownerAccountId = + canonicalUuid( + requiredString(members.get("ownerAccountId"), "ownerAccountId"), "ownerAccountId"); + return new StartSessionOperatorAction.Target(gameTemplateId, ownerAccountId); + } + + private static StartSessionOperatorAction.Mutation readMutation(JsonValue value) { + JsonObject object = requireObject(value, "mutation"); + Map members = + orderedMembers(object, List.of("clientIp"), Set.of("clientIp")); + JsonValue clientIp = members.get("clientIp"); + if (clientIp == null) { + return new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()); + } + if (clientIp instanceof JsonNull) { + throw invalid("clientIp may be absent or a string, but not null"); + } + if (!(clientIp instanceof JsonString string)) { + throw invalid("clientIp must be a string"); + } + String normalized = normalizeString(string.value(), 128, "clientIp"); + return new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of(normalized)); + } + + private static String requiredString(JsonValue value, String fieldName) { + if (!(value instanceof JsonString string)) { + throw invalid(fieldName + " must be a string"); + } + return normalizeString(string.value(), MAX_NORMALIZED_STRING_BYTES, fieldName); + } + + private static UUID canonicalUuid(String value, String fieldName) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + if (uuid.getMostSignificantBits() == 0L && uuid.getLeastSignificantBits() == 0L) { + throw invalid(fieldName + " must not be nil"); + } + return uuid; + } + + private static JsonObject requireObject(JsonValue value, String fieldName) { + if (!(value instanceof JsonObject object)) { + throw invalid(fieldName + " must be an object"); + } + return object; + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, Set optionalMembers) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid("object exceeds its member limit"); + } + Map normalizedMembers = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (normalizedMembers.putIfAbsent(key, member.value()) != null) { + throw invalid("object contains a duplicate or normalized-colliding member"); + } + if (!declaredOrder.contains(key)) { + throw invalid("object contains an unknown member"); + } + } + List expectedOrder = + declaredOrder.stream() + .filter(key -> normalizedMembers.containsKey(key) || !optionalMembers.contains(key)) + .toList(); + if (!new ArrayList<>(normalizedMembers.keySet()).equals(expectedOrder)) { + throw invalid("object members are missing or out of declared order"); + } + return normalizedMembers; + } + + private static MutationDigestV1.Value toGrammarValue(JsonValue value) { + if (value instanceof JsonString string) { + return MutationDigestV1.string(string.value()); + } + if (value instanceof JsonNumber number) { + return MutationDigestV1.number(number.lexeme()); + } + if (value instanceof JsonBoolean bool) { + return MutationDigestV1.bool(bool.value()); + } + if (value instanceof JsonNull) { + return MutationDigestV1.nullValue(); + } + if (value instanceof JsonArray array) { + return MutationDigestV1.array( + array.values().stream().map(StartSessionOperatorActionCodec::toGrammarValue).toList()); + } + if (value instanceof JsonObject object) { + List members = new ArrayList<>(object.members().size()); + for (JsonMember member : object.members()) { + String key = + normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + members.add(MutationDigestV1.member(key, toGrammarValue(member.value()))); + } + return MutationDigestV1.normalizeObject(members); + } + throw invalid("unsupported JSON value"); + } + + private static String normalizeString(String value, int maxUtf8Bytes, String fieldName) { + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw invalid(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(fieldName + " contains malformed Unicode"); + } + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private sealed interface JsonValue + permits JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, JsonArray { + byte[] rawToken(); + } + + private record JsonString(String value, byte[] rawToken) implements JsonValue { + private JsonString { + rawToken = rawToken.clone(); + } + } + + private record JsonNumber(String lexeme, byte[] rawToken) implements JsonValue { + private JsonNumber { + rawToken = rawToken.clone(); + } + } + + private record JsonBoolean(boolean value, byte[] rawToken) implements JsonValue { + private JsonBoolean { + rawToken = rawToken.clone(); + } + } + + private record JsonNull(byte[] rawToken) implements JsonValue { + private JsonNull { + rawToken = rawToken.clone(); + } + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members, byte[] rawToken) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + rawToken = rawToken.clone(); + } + } + + private record JsonArray(List values, byte[] rawToken) implements JsonValue { + private JsonArray { + values = List.copyOf(values); + rawToken = rawToken.clone(); + } + } + + /** Small bounded parser that retains source tokens and object occurrence order. */ + private static final class StrictJsonParser { + private final byte[] input; + private final String source; + private final int[] byteOffsets; + private int position; + + private StrictJsonParser(byte[] input) { + Objects.requireNonNull(input, "raw JSON is required"); + if (input.length > MAX_RAW_BYTES) { + throw invalid("raw JSON exceeds its byte limit"); + } + this.input = input.clone(); + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(this.input)); + this.source = decoded.toString(); + } catch (CharacterCodingException exception) { + throw invalid("raw JSON is not valid UTF-8"); + } + this.byteOffsets = computeByteOffsets(this.source, this.input.length); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != source.length()) { + throw invalid("raw JSON contains trailing tokens"); + } + return value; + } + + private JsonValue parseValue(int parentDepth) { + if (position >= source.length()) { + throw invalid("raw JSON ended before a value"); + } + char next = source.charAt(position); + if (next == '"') { + return parseString(); + } + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == '[') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseArray(parentDepth + 1); + } + if (next == 't') { + return parseLiteral("true", new JsonBoolean(true, new byte[0])); + } + if (next == 'f') { + return parseLiteral("false", new JsonBoolean(false, new byte[0])); + } + if (next == 'n') { + return parseLiteral("null", new JsonNull(new byte[0])); + } + return parseNumber(); + } + + private JsonValue parseLiteral(String literal, JsonValue placeholder) { + int start = position; + if (!source.startsWith(literal, position)) { + throw invalid("raw JSON contains an invalid token"); + } + position += literal.length(); + byte[] raw = rawToken(start, position); + if (placeholder instanceof JsonBoolean bool) { + return new JsonBoolean(bool.value(), raw); + } + return new JsonNull(raw); + } + + private JsonNumber parseNumber() { + int start = position; + while (position < source.length() && !isValueDelimiter(source.charAt(position))) { + position++; + } + if (start == position) { + throw invalid("raw JSON contains an invalid value token"); + } + byte[] raw = rawToken(start, position); + if (raw.length > MAX_NUMERIC_BYTES) { + throw invalid("numeric token exceeds its byte limit"); + } + return new JsonNumber(source.substring(start, position), raw); + } + + private JsonString parseString() { + int start = position; + position++; + StringBuilder value = new StringBuilder(); + while (position < source.length()) { + char current = source.charAt(position++); + if (current == '"') { + byte[] raw = rawToken(start, position); + String decoded = value.toString(); + requireUnicodeScalars(decoded, "string"); + return new JsonString(decoded, raw); + } + if (current == '\\') { + if (position >= source.length()) { + throw invalid("raw JSON ends inside a string escape"); + } + char escaped = source.charAt(position++); + switch (escaped) { + case '"' -> value.append('"'); + case '\\' -> value.append('\\'); + case '/' -> value.append('/'); + case 'b' -> value.append('\b'); + case 'f' -> value.append('\f'); + case 'n' -> value.append('\n'); + case 'r' -> value.append('\r'); + case 't' -> value.append('\t'); + case 'u' -> appendUnicodeEscape(value); + default -> throw invalid("raw JSON contains an invalid string escape"); + } + } else { + if (current < 0x20) { + throw invalid("raw JSON string contains an unescaped control character"); + } + value.append(current); + } + } + throw invalid("raw JSON string is unterminated"); + } + + private void appendUnicodeEscape(StringBuilder value) { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= source.length() + || source.charAt(position) != '\\' + || source.charAt(position + 1) != 'u') { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + value.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } else { + value.append(first); + } + } + + private char readHexCodeUnit() { + if (position + 4 > source.length()) { + throw invalid("raw JSON string contains a short Unicode escape"); + } + int value = 0; + for (int index = 0; index < 4; index++) { + char digit = source.charAt(position++); + int hex = Character.digit(digit, 16); + if (hex < 0 || digit > 0x7f) { + throw invalid("raw JSON string contains an invalid Unicode escape"); + } + value = (value << 4) | hex; + } + return (char) value; + } + + private JsonObject parseObject(int depth) { + int start = position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + while (true) { + if (position >= source.length() || source.charAt(position) != '"') { + throw invalid("raw JSON object member key must be a string"); + } + if (members.size() >= MAX_OBJECT_MEMBERS) { + throw invalid("raw JSON object exceeds its member limit"); + } + JsonString key = parseString(); + skipWhitespace(); + require(':'); + skipWhitespace(); + JsonValue value = parseValue(depth); + members.add(new JsonMember(key, value)); + skipWhitespace(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private JsonArray parseArray(int depth) { + int start = position++; + skipWhitespace(); + List values = new ArrayList<>(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + while (true) { + if (values.size() >= MAX_ARRAY_ELEMENTS) { + throw invalid("raw JSON array exceeds its element limit"); + } + values.add(parseValue(depth)); + skipWhitespace(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private byte[] rawToken(int start, int end) { + return Arrays.copyOfRange(input, byteOffsets[start], byteOffsets[end]); + } + + private void skipWhitespace() { + while (position < source.length()) { + char value = source.charAt(position); + if (value != ' ' && value != '\t' && value != '\r' && value != '\n') { + return; + } + position++; + } + } + + private boolean consume(char expected) { + if (position < source.length() && source.charAt(position) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) { + throw invalid("raw JSON punctuation or member order is invalid"); + } + } + + private static boolean isValueDelimiter(char value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private static int[] computeByteOffsets(String source, int expectedBytes) { + int[] offsets = new int[source.length() + 1]; + int characterIndex = 0; + int byteIndex = 0; + while (characterIndex < source.length()) { + int codePoint = source.codePointAt(characterIndex); + int characterCount = Character.charCount(codePoint); + int width = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + offsets[characterIndex] = byteIndex; + if (characterCount == 2) { + offsets[characterIndex + 1] = byteIndex; + } + characterIndex += characterCount; + byteIndex += width; + offsets[characterIndex] = byteIndex; + } + if (byteIndex != expectedBytes) { + throw invalid("raw JSON UTF-8 framing is inconsistent"); + } + return offsets; + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java new file mode 100644 index 0000000000..de35ef6b9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java @@ -0,0 +1,225 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class StartSessionOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = + "/operator/start-session-mutation-digest-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void matchesSharedActionVectors() throws IOException { + JsonNode vectors = fixture().path("vectors"); + String baseDigest = null; + String changedTargetDigest = null; + String changedScopeDigest = null; + String changedReasonDigest = null; + String composedDigest = null; + String decomposedDigest = null; + String absentClientIpDigest = null; + String emptyClientIpDigest = null; + + for (JsonNode vector : vectors) { + byte[] raw = rawVectorBytes(vector); + String name = vector.path("name").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(raw)) + .as("vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + StartSessionOperatorAction action = StartSessionOperatorActionCodec.decode(raw); + byte[] preimage = StartSessionOperatorActionCodec.canonicalPreimage(action); + String digest = StartSessionOperatorActionCodec.mutationDigest(action); + assertThat(hex(preimage)) + .as("preimage for %s", name) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(digest).as("digest for %s", name).isEqualTo(vector.path("digest").asText()); + switch (name) { + case "base" -> baseDigest = digest; + case "changed-target" -> changedTargetDigest = digest; + case "changed-scope" -> changedScopeDigest = digest; + case "changed-audit-reason" -> changedReasonDigest = digest; + case "client-ip-absent" -> absentClientIpDigest = digest; + case "client-ip-empty" -> emptyClientIpDigest = digest; + case "unicode-composed" -> composedDigest = digest; + case "unicode-decomposed" -> decomposedDigest = digest; + default -> { + // Individual golden values above prove the remaining mutation vectors. + } + } + } + + assertThat(absentClientIpDigest).isNotEqualTo(emptyClientIpDigest); + assertThat(composedDigest).isEqualTo(decomposedDigest); + assertThat(baseDigest) + .isNotEqualTo(absentClientIpDigest) + .isNotEqualTo(changedTargetDigest) + .isNotEqualTo(changedScopeDigest) + .isNotEqualTo(changedReasonDigest); + } + + @Test + void matchesSharedGenericValueGrammarVectors() throws IOException { + java.util.Map encodings = new java.util.HashMap<>(); + for (JsonNode vector : fixture().path("grammarVectors")) { + String name = vector.path("name").asText(); + String kind = vector.path("kind").asText(); + if ("numberLexeme".equals(kind)) { + String rawLexeme = vector.path("rawLexeme").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy( + () -> StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)) + .as("numeric lexeme vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + String encoded = + hex(StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)); + assertThat(encoded) + .as("numeric lexeme vector %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encoded); + continue; + } + if ("reject".equals(kind)) { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw)) + .as("grammar vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + byte[] encoded; + if ("absent".equals(kind)) { + encoded = StartSessionOperatorActionCodec.absentGrammarValueForTest(); + } else { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + encoded = StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw); + } + String encodedHex = hex(encoded); + assertThat(encodedHex) + .as("canonical value for %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encodedHex); + } + + assertThat(encodings.get("absent")).isNotEqualTo(encodings.get("null")); + assertThat(encodings.get("number-one")).isNotEqualTo(encodings.get("string-one")); + assertThat(encodings.get("number-signed-zero")).isEqualTo(encodings.get("number-zero")); + assertThat(encodings.get("unicode-key-composed")) + .isEqualTo(encodings.get("unicode-key-decomposed")); + } + + @Test + void exposesOnlyTypedImmutableStartSessionFields() throws IOException { + JsonNode base = findVector("base"); + StartSessionOperatorAction action = + StartSessionOperatorActionCodec.decode(rawVectorBytes(base)); + + assertThat(StartSessionOperatorAction.OWNER_SERVICE).isEqualTo("game-session-service"); + assertThat(action.targetOwner()).isEqualTo("game-session-service"); + assertThat(action.actionFamilySchemaId()).isEqualTo("firemud.game-session.start-session"); + assertThat(action.actionFamilySchemaVersion()).isEqualTo("1"); + assertThat(action.expectedVersion()) + .isEqualTo(StartSessionOperatorAction.ExpectedVersion.ABSENT); + assertThat(action.scope().tenantId().toString()) + .isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(action.target().gameTemplateId()).isEqualTo(42L); + assertThat(action.mutation().clientIp()) + .isInstanceOf(StartSessionOperatorAction.StringClientIp.class); + assertThat(action.auditReason()).isEqualTo("scheduled launch"); + } + + @Test + void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedRaw = new byte[StartSessionOperatorActionCodec.MAX_RAW_BYTES + 1]; + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(oversizedRaw)) + .isInstanceOf(IllegalArgumentException.class); + + String base = findVector("base").path("input").asText(); + String oversizedReason = base.replace("scheduled launch", "x".repeat(1_001)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedReason.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String oversizedClientIp = base.replace("192.0.2.1", "x".repeat(129)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedClientIp.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsObjectMemberAndArrayElementLimitViolations() { + String tooManyMembers = "{" + String.join(",", Collections.nCopies(17, "\"k\":0")) + "}"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyMembers.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooManyElements = "[" + String.join(",", Collections.nCopies(65, "0")) + "]"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyElements.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooDeep = "[".repeat(9) + "0" + "]".repeat(9); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooDeep.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + StartSessionOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing shared StartSession digest vector resource"); + } + return JSON.readTree(stream); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(vector.path("name").asText())) { + return vector; + } + } + throw new IOException("missing vector: " + name); + } + + private static byte[] rawVectorBytes(JsonNode vector) { + if (vector.has("rawHex")) { + return java.util.HexFormat.of().parseHex(vector.path("rawHex").asText()); + } + return vector.path("input").asText().getBytes(StandardCharsets.UTF_8); + } + + private static String hex(byte[] bytes) { + return java.util.HexFormat.of().formatHex(bytes); + } +} diff --git a/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json new file mode 100644 index 0000000000..a1874220fa --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json @@ -0,0 +1,167 @@ +{ + "schemaId": "firemud.game-session.start-session", + "schemaVersion": "1", + "vectors": [ + { + "name": "base", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "f81e35e943d51078a1d1c5eb7f3175bedbd7e704f55fe7b450050b852dd62e29" + }, + { + "name": "changed-target", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"43\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343331343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "5c736b3aa5c0772f0edef9fbf00a60b585ab99cccf774cb08196f7eb5cca346d" + }, + { + "name": "changed-scope", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"44444444-4444-4444-8444-444444444444\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "cdb171f110e99654085d935f9dd0c9d0dd46877272976080b01f84320ec45008" + }, + { + "name": "changed-audit-reason", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"operator launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131353a6f70657261746f72206c61756e6368", + "digest": "43ac8a4e4c8618c090ed7cd298a223e42dffca4519c7a1c38509b8cc1eb16867" + }, + { + "name": "client-ip-absent", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "01b67879242b7213c9dd9dafbed8a4ed5cbec72ba671d9a04c263bf3b52e3195" + }, + { + "name": "client-ip-empty", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a737472696e6731303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "880d0f5718ce3f1150d559b6e1df62bbe22249cfb95774b3040715be29966ec1" + }, + { + "name": "unicode-composed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"caf\\u00e9 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "unicode-decomposed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"cafe\\u0301 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "client-ip-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":null},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":null,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-present", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":1,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "wrong-type-client-ip", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":7},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "duplicate-root-key", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "normalized-key-collision", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"t\\u00e9\":\"x\",\"te\\u0301\":\"y\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "unknown-member", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\",\"extra\":true},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "missing-audit-reason", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{}}" + }, + { + "name": "wrong-scope-member-order", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"targetNamespace\":\"firemud\",\"tenantId\":\"22222222-2222-4222-8222-222222222222\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "malformed-unicode", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"\\uD800\"}" + }, + { + "name": "invalid-utf8", + "accepted": false, + "rawHex": "7b22616374696f6e46616d696c79536368656d614964223a22666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e222c22616374696f6e46616d696c79536368656d6156657273696f6e223a2231222c2273636f7065223a7b2274656e616e744964223a2232323232323232322d323232322d343232322d383232322d323232323232323232323232222c227461726765744e616d657370616365223a22666972656d7564227d2c22746172676574223a7b2267616d6554656d706c6174654964223a223432222c226f776e65724163636f756e744964223a2233333333333333332d333333332d343333332d383333332d333333333333333333333333227d2c226d75746174696f6e223a7b22636c69656e744970223a223139322e302e322e31227d2c226175646974526561736f6e223a22ff227d" + }, + { + "name": "numeric-template-id-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":42,\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "non-canonical-template-id-string", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"042\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "template-id-overflow-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"9223372036854775808\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "nil-owner-account-id", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"00000000-0000-0000-0000-000000000000\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + } + ], + "grammarVectors": [ + {"name": "absent", "kind": "absent", "canonicalValueHex": "363a616273656e7430303a"}, + {"name": "null", "kind": "raw", "rawValue": "null", "canonicalValueHex": "343a6e756c6c31303a"}, + {"name": "number-one", "kind": "raw", "rawValue": "1", "canonicalValueHex": "363a6e756d62657231313a31"}, + {"name": "string-one", "kind": "raw", "rawValue": "\"1\"", "canonicalValueHex": "363a737472696e6731313a31"}, + {"name": "number-ten-trailing-zeroes", "kind": "raw", "rawValue": "10.000", "canonicalValueHex": "363a6e756d62657231323a3130"}, + {"name": "number-negative-decimal", "kind": "raw", "rawValue": "-12.3400", "canonicalValueHex": "363a6e756d62657231363a2d31322e3334"}, + {"name": "number-signed-zero", "kind": "raw", "rawValue": "-0.00", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "number-zero", "kind": "raw", "rawValue": "0", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "array-order", "kind": "raw", "rawValue": "[1,\"1\",null]", "canonicalValueHex": "353a61727261793133363a313a33363a6e756d62657231313a31363a737472696e6731313a31343a6e756c6c31303a"}, + {"name": "unicode-key-composed", "kind": "raw", "rawValue": "{\"\\u00e9\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "unicode-key-decomposed", "kind": "raw", "rawValue": "{\"e\\u0301\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "malformed-surrogate-rejected", "kind": "reject", "rawValue": "\"\\uD800\""}, + {"name": "nesting-depth-rejected", "kind": "reject", "rawValue": "[[[[[[[[[0]]]]]]]]]"}, + {"name": "duplicate-object-key-rejected", "kind": "reject", "rawValue": "{\"a\":1,\"a\":2}"}, + {"name": "normalized-object-key-collision-rejected", "kind": "reject", "rawValue": "{\"\\u00e9\":1,\"e\\u0301\":2}"}, + {"name": "number-space-prefix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": " 1"}, + {"name": "number-space-suffix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1 "}, + {"name": "number-trailing-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1."}, + {"name": "number-leading-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": ".5"}, + {"name": "number-nan-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "NaN"}, + {"name": "number-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "Infinity"}, + {"name": "number-negative-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "-Infinity"}, + {"name": "number-exponent-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1e3"}, + {"name": "number-plus-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "+1"}, + {"name": "number-leading-zero-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "01"}, + {"name": "number-exponent-rejected", "kind": "reject", "rawValue": "1e3"}, + {"name": "number-plus-rejected", "kind": "reject", "rawValue": "+1"}, + {"name": "number-leading-zero-rejected", "kind": "reject", "rawValue": "01"} + ] +} From dcccbaf7b38db50bfab6694ac11280eb8f36e489 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:31:43 +1300 Subject: [PATCH 13/29] test(game-design): expose publication mechanics failure diagnostics --- ...shAttemptServiceTransactionIntegrationTest.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index be0e502429..218a5f35d3 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -640,8 +640,18 @@ private record SelectedPublicationFixture( private static void assertMechanicsSnapshot( Object snapshot, String expectedStatus, String expectedFailureMessage) { - assertThat(snapshotValue(snapshot, "status")).isEqualTo(expectedStatus); - assertThat(snapshotValue(snapshot, "failureMessage")).isEqualTo(expectedFailureMessage); + String actualStatus = snapshotValue(snapshot, "status"); + String actualFailureCode = snapshotValue(snapshot, "failureCode"); + String actualFailureMessage = snapshotValue(snapshot, "failureMessage"); + String failureContext = + "publication mechanics snapshot: status=" + + actualStatus + + ", failureCode=" + + actualFailureCode + + ", failureMessage=" + + actualFailureMessage; + assertThat(actualStatus).as(failureContext).isEqualTo(expectedStatus); + assertThat(actualFailureMessage).as(failureContext).isEqualTo(expectedFailureMessage); } private AtomicReference captureControlPlaneDigestFailure() { From 919501c6f99642edb7958d8593f5afd2af93110e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:54:32 +1300 Subject: [PATCH 14/29] fix: bind publication seal to explicit read committed transaction --- .../service/impl/PublishAttemptServiceImpl.java | 5 ++++- ...AttemptServiceTransactionIntegrationTest.java | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index 84185929fa..0ecce61d7e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -46,7 +47,9 @@ public T executeScriptPatchTransaction(Supplier operation) { } @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) + @Transactional( + propagation = Propagation.REQUIRES_NEW, + isolation = Isolation.READ_COMMITTED) public T executeFullVersionTransaction(Supplier operation) { try { return operation.get(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index fd64ec5161..b9d9f20706 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -61,6 +61,7 @@ import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -121,6 +122,21 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; + @Test + void fullVersionSealTransactionUsesExplicitReadCommittedIsolation() { + AtomicReference isolation = new AtomicReference<>(); + + publishAttemptService.executeFullVersionTransaction( + () -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + isolation.set(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + return null; + }); + + assertThat(isolation.get()).isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + @Test void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { Game game = new Game(); From 7af572b66d5901f0923dafd9dfadac2fef4380e0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:58:21 +1300 Subject: [PATCH 15/29] style: format explicit publication seal isolation --- .../gamedesign/service/impl/PublishAttemptServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index 0ecce61d7e..f4d6df9c29 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -47,9 +47,7 @@ public T executeScriptPatchTransaction(Supplier operation) { } @Override - @Transactional( - propagation = Propagation.REQUIRES_NEW, - isolation = Isolation.READ_COMMITTED) + @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED) public T executeFullVersionTransaction(Supplier operation) { try { return operation.get(); From ef22087afdd2b67ecc63b4cd01a2ec70b8a33dcc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:01:17 +1300 Subject: [PATCH 16/29] feat: preserve committed Account actor proof and StartSession reservation --- .../start-session-action-schema.md | 4 + .../platform-operations-and-delivery.md | 2 + services/account-service/build.gradle.kts | 1 + .../config/AccountJwtJwksApiBinding.java | 1260 +++++ .../AccountJwtReadinessTrustBinding.java | 480 ++ ...ountJwtSignerMaterializerTrustBinding.java | 404 ++ .../AccountJwtValidatorInventoryBinding.java | 842 ++++ ...tControlUiCommittedIssuanceRepository.java | 280 ++ ...ountGameplayDelegationPendingIdentity.java | 36 + .../AccountJwtJwksPublicationRepository.java | 1315 +++++ .../AccountJwtReadinessProbeRepository.java | 4246 +++++++++++++++++ ...ccountJwtSignerDesiredStateRepository.java | 4178 ++++++++++++++++ ...ccountJwtValidatorInventoryRepository.java | 280 ++ .../AccountControlUiCurrentActorVerifier.java | 848 ++++ .../AccountControlUiRegistryReader.java | 212 + ...tCoordinationPinnedConnectionProvider.java | 14 + .../AccountJwtJwksConfigMapClient.java | 704 +++ .../session/AccountJwtJwksTrustedSource.java | 761 +++ ...AccountJwtReadinessProbeOwnerSelector.java | 165 + ...untJwtReadinessReceiverInvocationPort.java | 593 +++ .../AccountJwtValidatorInventorySource.java | 1290 +++++ .../AccountMountedJwtSignerBundle.java | 1269 +++++ ..._account_jwt_readiness_per_pod_closure.sql | 777 +++ ...t_jwt_signer_promotion_receipt_binding.sql | 126 + .../V41__account_jwt_signer_desired_state.sql | 405 ++ ...nt_jwt_signer_materialization_readback.sql | 327 ++ .../V43__account_jwt_jwks_prepublication.sql | 600 +++ .../V45__account_jwt_readiness_probes.sql | 466 ++ ...account_jwt_signer_promotion_lifecycle.sql | 570 +++ ...t_jwt_readiness_single_delivery_claims.sql | 125 + ...ount_jwt_validator_inventory_snapshots.sql | 67 + ..._account_control_ui_committed_issuance.sql | 119 + ...ttedIssuanceRepositoryIntegrationTest.java | 595 +++ .../AccountJwtJwksApiTransportTest.java | 772 +++ ...countJwtJwksPublicationRepositoryTest.java | 226 + ...ccountJwtReadinessProbeRepositoryTest.java | 133 + ...ntJwtSignerDesiredStateRepositoryTest.java | 748 +++ ...ountControlUiCurrentActorVerifierTest.java | 890 ++++ .../AccountControlUiRegistryReaderTest.java | 160 + .../AccountJwtJwksConfigMapClientTest.java | 591 +++ .../AccountJwtJwksTrustedSourceTest.java | 677 +++ ...ssionPreAuthorizationReservationTuple.java | 381 ++ ...nPreAuthorizationReservationTupleTest.java | 134 + .../ControlUiJwtProfileValidator.java | 102 + ...essionAccountDelegationRegistryRecord.java | 891 ++++ .../PlayerBootstrapJwtProfileValidator.java | 39 + .../ControlUiJwtProfileValidatorTest.java | 219 + ...ionPreAuthorizationReservationService.java | 360 ++ ...ssionPreAuthorizationReservationTuple.java | 139 + ...PreAuthorizationReservationRepository.java | 415 ++ ...session_pre_authorization_reservations.sql | 27 + ...ionReservationPostgresIntegrationTest.java | 252 + ...reAuthorizationReservationServiceTest.java | 164 + ...nPreAuthorizationReservationTupleTest.java | 171 + 54 files changed, 30852 insertions(+) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java create mode 100644 services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql create mode 100644 services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql create mode 100644 services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql create mode 100644 services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql create mode 100644 services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql create mode 100644 services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql create mode 100644 services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql create mode 100644 services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md index b3b3432495..467529e809 100644 --- a/design/architecture/microservices/game-session-service/start-session-action-schema.md +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -1,5 +1,9 @@ # StartSession Operator Action Schema +## Implementation status + +The shared typed action, digest codec, and pre-authorization reservation tuple are implemented. Logging & Admin has durable reservation, claim expiry, and read-only recovery-claim seams; Account has read-only verification of existing committed tenant-scoped control-ui issuance against its protected signer/registry and current membership evidence. These are prerequisites, not an executable StartSession route. Account operator-reference issuance/redemption, post-authorization owner handoff, canonical Game Session consumption, and physical cross-service proof remain incomplete. No external route or runtime activation is enabled by this boundary. + ## Normative contract This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 05eba37107..f667aa3b22 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -88,6 +88,8 @@ The exact source-run publication handoff is implemented locally in the runtime p ## Operator Write Boundary Status +The StartSession prerequisite now includes the shared action/digest and pre-authorization tuple, Logging & Admin's durable reservation/claim/recovery seams, and Account's read-only current tenant-scoped control-ui actor verification. It does not issue or redeem operator references, forward owner mutations, or provide canonical Game Session execution. The [StartSession schema owner](../../architecture/microservices/game-session-service/start-session-action-schema.md#implementation-status) records this partial boundary; physical reservation/authority integration, owner handoff, and live launch proof remain open. + The tracker separates implemented fail-closed ingress stubs from supported durable operator workflows and the target external ingress contract. Game Session `/sessions*` routes remain internal/owner-local. Logging & Admin feature-flag and scoped tick ingress stubs remain externally unavailable because they do not currently forward and the complete [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) owner-write gate is not implemented or proved. Moderation and appeal implementation status remains owned by the [Logging & Admin moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md) contract; quota overrides, broader remediation, external session-lifecycle forwarding, and other unproved owner mutations remain gated or target-only. ## Canonical Design Sources diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..388e86ce55 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -12,6 +12,7 @@ firemudJooq { } dependencies { + implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java new file mode 100644 index 0000000000..f92fc8418f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java @@ -0,0 +1,1260 @@ +package net.firedevops.firemud.accountservice.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.IDN; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +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; + +/** + * Independently protected, default-inactive trust for Account's fixed public-JWKS Kubernetes + * ConfigMap calls. This is deliberately not a Spring component: lifecycle wiring must opt in. + */ +public final class AccountJwtJwksApiBinding { + public static final int MAX_BINDING_BYTES = 16 * 1024; + private static final int MAX_CA_BYTES = 128 * 1024; + private static final int MAX_BEARER_BYTES = 16 * 1024; + private static final int MAX_RESPONSE_BYTES = 1024 * 1024; + private static final int MAX_REQUEST_BYTES = 1024 * 1024; + private static final String BINDING_VERSION = "account-jwt-jwks-api-binding/v1"; + private static final String ACCOUNT_SERVICE_ACCOUNT = "account-service"; + private static final Path TRUST_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final Path TRUST_BINDING_PATH = TRUST_ROOT.resolve("binding.json"); + private static final Path TRUST_CA_PATH = TRUST_ROOT.resolve("serving-ca.pem"); + + private static final Path TOKEN_ROOT = protectedTokenRoot(); + + private static final Path TOKEN_PATH = TOKEN_ROOT.resolve("token"); + + private static final Path CANONICAL_TOKEN_ROOT = canonicalProjectedTokenRoot(); + + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern NAMESPACE = ENVIRONMENT; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern BEARER = Pattern.compile("[!-~]{1,16384}"); + private static final Set CONFIG_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "apiServerUrl", + "tlsServerName", + "servingCaPath", + "servingCaSha256", + "bearerTokenPath", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedApiUsername", + "bindingDigest"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account's bearer credential is read only from this fixed protected projected-token root.") + private static Path protectedTokenRoot() { + return Path.of("/var/run/secrets/firemud/account-jwt-api-token"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "This exact canonical root remains the only alternate projected-token mount accepted by the protected Account API boundary.") + private static Path canonicalProjectedTokenRoot() { + return Path.of("/run/secrets/firemud/account-jwt-api-token"); + } + + private final boolean enabled; + private final String protectedBindingPath; + private final Duration requestTimeout; + private final ProtectedState testProtectedState; + private final ProtectedPaths protectedPaths; + private final AtomicReference acceptedIdentity = new AtomicReference<>(); + + /** Creates an inert binding. No Spring activation or ambient Kubernetes configuration exists. */ + public AccountJwtJwksApiBinding() { + this(false, ""); + } + + /** + * Creates an explicitly selected binding. The selected file still has to authorize the exact + * Account endpoint, trust anchor, cluster/namespace incarnation, and authenticated principal. + */ + public AccountJwtJwksApiBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String configuredPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.protectedBindingPath = + TRUST_BINDING_PATH.toString().equals(configuredPath) ? configuredPath : ""; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = + new ProtectedPaths( + TRUST_ROOT, TRUST_BINDING_PATH, TRUST_CA_PATH, TOKEN_ROOT, TOKEN_PATH, false); + } + + private AccountJwtJwksApiBinding(Duration requestTimeout, ProtectedState testProtectedState) { + this.enabled = true; + this.protectedBindingPath = ""; + this.requestTimeout = requestTimeout; + this.testProtectedState = testProtectedState; + this.protectedPaths = null; + } + + private AccountJwtJwksApiBinding(String bindingPath, ProtectedPaths protectedPaths) { + this.enabled = true; + this.protectedBindingPath = bindingPath; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = protectedPaths; + } + + static AccountJwtJwksApiBinding forProtectedFilesTest( + Path bindingPath, Path trustRoot, Path caPath, Path tokenRoot, Path tokenPath) { + Objects.requireNonNull(bindingPath, "test binding path is required"); + Objects.requireNonNull(trustRoot, "test trust root is required"); + Objects.requireNonNull(caPath, "test CA path is required"); + Objects.requireNonNull(tokenRoot, "test token root is required"); + Objects.requireNonNull(tokenPath, "test token path is required"); + Path normalizedBinding = bindingPath.toAbsolutePath().normalize(); + Path normalizedTrustRoot = trustRoot.toAbsolutePath().normalize(); + Path normalizedCa = caPath.toAbsolutePath().normalize(); + Path normalizedTokenRoot = tokenRoot.toAbsolutePath().normalize(); + Path normalizedToken = tokenPath.toAbsolutePath().normalize(); + if (!normalizedBinding.equals(normalizedTrustRoot.resolve("binding.json")) + || !normalizedCa.equals(normalizedTrustRoot.resolve("serving-ca.pem")) + || !normalizedToken.equals(normalizedTokenRoot.resolve("token"))) { + throw new IllegalArgumentException("Protected Account JWT test paths are invalid"); + } + ProtectedPaths paths = + new ProtectedPaths( + normalizedTrustRoot, + normalizedBinding, + normalizedCa, + normalizedTokenRoot, + normalizedToken, + true); + return new AccountJwtJwksApiBinding(normalizedBinding.toString(), paths); + } + + /** + * Supplies trusted in-memory binding material only to package-local transport tests. It still + * exercises the production pinned-CA HTTPS sender and cannot install a custom HTTP client. + */ + static AccountJwtJwksApiBinding forTransportTest( + ParsedBinding binding, byte[] caBytes, String bearerToken, Duration requestTimeout) { + Objects.requireNonNull(binding, "transport test binding is required"); + Objects.requireNonNull(caBytes, "transport test CA is required"); + Objects.requireNonNull(requestTimeout, "transport test timeout is required"); + if (caBytes.length == 0 + || caBytes.length > MAX_CA_BYTES + || !sha256(caBytes).equals(binding.servingCaSha256()) + || !"https".equalsIgnoreCase(binding.apiServer().getScheme()) + || binding.apiServer().getHost() == null + || !binding.apiServer().getHost().equalsIgnoreCase(binding.tlsServerName()) + || !binding + .expectedApiUsername() + .equals("system:serviceaccount:" + binding.namespace() + ":" + ACCOUNT_SERVICE_ACCOUNT) + || bearerToken == null + || !BEARER.matcher(bearerToken).matches() + || requestTimeout.isZero() + || requestTimeout.isNegative() + || requestTimeout.compareTo(Duration.ofSeconds(8)) > 0) { + throw new IllegalArgumentException("Account JWT JWKS transport test binding is invalid"); + } + byte[] caSnapshot = caBytes.clone(); + Set readOnly = Set.of(PosixFilePermission.OWNER_READ); + FileIdentity bindingIdentity = testFileIdentity("test-binding", new byte[] {1}, readOnly); + FileIdentity caIdentity = testFileIdentity("test-ca", caSnapshot, readOnly); + FileIdentity bearerIdentity = + testFileIdentity( + binding.bearerTokenPath().toString(), + bearerToken.getBytes(StandardCharsets.UTF_8), + readOnly); + TrustIdentity identity = + new TrustIdentity( + bindingIdentity, + caIdentity, + credentialPolicy(bearerIdentity), + binding.bindingDigest(), + ""); + return new AccountJwtJwksApiBinding( + requestTimeout, + new ProtectedState(binding, caSnapshot, bearerToken, identity, bearerIdentity)); + } + + /** Returns non-secret pinned endpoint and identity fields after rechecking protected files. */ + public ParsedBinding current() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return acceptCurrentProtectedState().config(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Opens one fixed-endpoint operation with a single bounded bearer snapshot. */ + public ApiOperation beginOperation() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return new ApiOperation(acceptCurrentProtectedState()); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ProtectedState credentialSnapshot, ApiCall call, byte[] requestBody) { + return send(credentialSnapshot, call, requestBody, null); + } + + private ApiResponse send( + ProtectedState credentialSnapshot, + ApiCall call, + byte[] requestBody, + String protectedInventoryPath) { + Objects.requireNonNull(call, "Kubernetes API call is required"); + if (!enabled || protectedBindingPath.isBlank() || credentialSnapshot == null) { + throw new BindingRejectedException(); + } + if (requestBody != null && requestBody.length > MAX_REQUEST_BYTES) { + throw new BindingRejectedException(); + } + validateCallBody(call, requestBody); + ProtectedState state = recheckProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (!baseline.equals(credentialSnapshot.identity()) + || !credentialSnapshot.bearerIdentity().equals(state.bearerIdentity())) { + throw new BindingRejectedException(); + } + + HttpClient client; + try { + client = createHttpClient(credentialSnapshot.caBytes()); + } catch (Exception ex) { + throw new BindingRejectedException(); + } + if ((call == ApiCall.READ_VALIDATOR_DEPLOYMENT + || call == ApiCall.LIST_VALIDATOR_PODS + || call == ApiCall.READ_VALIDATOR_REPLICA_SET) + != (protectedInventoryPath != null)) { + throw new BindingRejectedException(); + } + URI uri = + credentialSnapshot + .config() + .apiServer() + .resolve( + protectedInventoryPath == null + ? call.path(credentialSnapshot.config().namespace()) + : protectedInventoryPath); + HttpRequest.Builder request = + HttpRequest.newBuilder(uri) + .timeout(requestTimeout) + .header("Accept", "application/json") + .header("Authorization", "Bearer " + credentialSnapshot.bearerToken()); + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + request.header("Content-Type", "application/merge-patch+json"); + } else if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + request.header("Content-Type", "application/json"); + } + if (requestBody == null) { + request.method(call.method(), HttpRequest.BodyPublishers.noBody()); + } else { + request.method(call.method(), HttpRequest.BodyPublishers.ofByteArray(requestBody)); + } + + // Catch changed or withdrawn trust after client construction and immediately before send. + ProtectedState beforeSend = recheckProtectedState(); + if (!baseline.equals(beforeSend.identity()) + || !credentialSnapshot.bearerIdentity().equals(beforeSend.bearerIdentity())) { + throw new BindingRejectedException(); + } + long responseDeadlineNanos = System.nanoTime() + requestTimeout.toNanos(); + try { + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofInputStream()); + try (java.io.InputStream body = response.body()) { + ExecutorService bodyReader = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "account-jwks-api-response-reader"); + thread.setDaemon(true); + return thread; + }); + Future bodyFuture = bodyReader.submit(() -> readBounded(body, MAX_RESPONSE_BYTES)); + try { + long remainingNanos = responseDeadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new TimeoutException(); + } + return new ApiResponse( + response.statusCode(), bodyFuture.get(remainingNanos, TimeUnit.NANOSECONDS)); + } catch (TimeoutException ex) { + bodyFuture.cancel(true); + throw new IOException("Kubernetes API response exceeded its deadline"); + } finally { + bodyReader.shutdownNow(); + } + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new ApiTransportException(); + } catch (Exception ex) { + throw new ApiTransportException(); + } + } + + private ProtectedState recheckProtectedState() { + try { + return acceptCurrentProtectedState(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Strict parser is exposed for deterministic format tests, not as an activation path. */ + public static ParsedBinding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Account JWT JWKS API binding is unavailable"); + } + try { + String text = decodeUtf8(bytes); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject() || root.size() != CONFIG_FIELDS.size()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + Map supplied = new LinkedHashMap<>(); + for (Map.Entry field : root.properties()) { + if (!CONFIG_FIELDS.contains(field.getKey()) + || supplied.putIfAbsent(field.getKey(), field.getValue()) != null) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + if (!supplied.keySet().equals(CONFIG_FIELDS) + || !"true".equals(requiredText(root, "enabled", 5)) + || !BINDING_VERSION.equals(requiredText(root, "version", 80))) { + throw new IllegalArgumentException("Account JWT JWKS API binding is disabled"); + } + + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiUsername = requiredText(root, "expectedApiUsername", 256); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !NAMESPACE.matcher(namespace).matches() + || !apiUsername.equals( + "system:serviceaccount:" + namespace + ":" + ACCOUNT_SERVICE_ACCOUNT)) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + + URI apiServer = parseApiServer(requiredText(root, "apiServerUrl", 512)); + String tlsServerName = requiredText(root, "tlsServerName", 253); + String asciiTlsName = canonicalDnsName(tlsServerName); + if (!asciiTlsName.equalsIgnoreCase(apiServer.getHost())) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is not pinned"); + } + String caPath = requiredText(root, "servingCaPath", 1024); + String caSha256 = requiredText(root, "servingCaSha256", 64); + String tokenPath = requiredText(root, "bearerTokenPath", 1024); + if (!SHA256.matcher(caSha256).matches()) { + throw new IllegalArgumentException("Account JWT JWKS API CA pin is malformed"); + } + Path servingCaPath = absoluteProtectedPath(caPath); + Path bearerTokenPath = absoluteProtectedPath(tokenPath); + String suppliedDigest = requiredText(root, "bindingDigest", 64); + if (!SHA256.matcher(suppliedDigest).matches() + || !suppliedDigest.equals(computeBindingDigest(root))) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is invalid"); + } + return new ParsedBinding( + revision, + environmentId, + clusterId, + apiServer, + asciiTlsName, + servingCaPath, + caSha256, + bearerTokenPath, + namespace, + clusterUid, + namespaceUid, + apiUsername, + suppliedDigest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + + public static String computeBindingDigest(JsonNode protectedBinding) { + if (protectedBinding == null || !protectedBinding.isObject()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + try { + Map content = new LinkedHashMap<>(); + for (String field : CONFIG_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode value = protectedBinding.get(field); + if (value == null || !value.isValueNode()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + content.put(field, value.asText()); + } + } + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(STRICT_JSON.writeValueAsString(content)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is unavailable"); + } + } + + private ProtectedState readCurrentProtectedState() throws Exception { + if (testProtectedState != null) { + return testProtectedState; + } + Path bindingPath = absoluteProtectedPath(protectedBindingPath); + if (protectedPaths == null + || !bindingPath.equals(protectedPaths.bindingPath()) + || (!protectedPaths.testOnly() + && (!bindingPath.equals(TRUST_BINDING_PATH) + || !protectedPaths.trustRoot().equals(TRUST_ROOT) + || !protectedPaths.caPath().equals(TRUST_CA_PATH) + || !protectedPaths.tokenRoot().equals(TOKEN_ROOT) + || !protectedPaths.tokenPath().equals(TOKEN_PATH)))) { + throw new BindingRejectedException(); + } + Path canonicalTokenRoot = resolveTrustedTokenRoot(protectedPaths); + if (!protectedPaths.testOnly()) { + verifyProtectedDirectoryChain(TRUST_ROOT); + verifyProtectedDirectoryChain(canonicalTokenRoot); + } + ProtectedFile bindingFile = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + ParsedBinding config = parseProtectedBytes(bindingFile.bytes()); + if (!config.servingCaPath().equals(protectedPaths.caPath()) + || !config.bearerTokenPath().equals(protectedPaths.tokenPath())) { + throw new BindingRejectedException(); + } + ProtectedFile caFile = readProtectedFile(config.servingCaPath(), MAX_CA_BYTES); + ProtectedFile tokenFile = + readBearerProtectedFile(config.bearerTokenPath(), protectedPaths.tokenRoot()); + String caDigest = sha256(caFile.bytes()); + if (!caDigest.equals(config.servingCaSha256())) { + throw new BindingRejectedException(); + } + String token = decodeUtf8(tokenFile.bytes()); + if (!BEARER.matcher(token).matches()) { + throw new BindingRejectedException(); + } + TrustIdentity identity = + new TrustIdentity( + bindingFile.identity(), + caFile.identity(), + credentialPolicy(tokenFile.identity()), + config.bindingDigest(), + canonicalTokenRoot.toString()); + return new ProtectedState(config, caFile.bytes(), token, identity, tokenFile.identity()); + } + + private static CredentialPolicyIdentity credentialPolicy(FileIdentity identity) { + return new CredentialPolicyIdentity( + identity.path(), identity.ownerUid(), identity.groupId(), identity.permissions()); + } + + private ProtectedState acceptCurrentProtectedState() throws Exception { + ProtectedState state = readCurrentProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (baseline == null) { + acceptedIdentity.compareAndSet(null, state.identity()); + baseline = acceptedIdentity.get(); + } + if (baseline == null || !baseline.equals(state.identity())) { + throw new BindingRejectedException(); + } + return state; + } + + private static HttpClient createHttpClient(byte[] caBytes) throws Exception { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + List certificates = + List.copyOf(certificateFactory.generateCertificates(new ByteArrayInputStream(caBytes))); + if (certificates.isEmpty() || certificates.size() > 16) { + throw new BindingRejectedException(); + } + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + if (!(certificate instanceof X509Certificate x509)) { + throw new BindingRejectedException(); + } + x509.checkValidity(); + if (x509.getBasicConstraints() < 0) { + throw new BindingRejectedException(); + } + trustStore.setCertificateEntry("account-jwks-ca-" + index++, x509); + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers.getTrustManagers(), null); + SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + return HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER) + .version(HttpClient.Version.HTTP_1_1) + .sslContext(sslContext) + .sslParameters(sslParameters) + .proxy(DIRECT_ONLY_PROXY) + .build(); + } + + private static final ProxySelector DIRECT_ONLY_PROXY = + new ProxySelector() { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + // No proxy exists; connection failures are handled by the bounded API call. + } + }; + + private static byte[] readBounded(java.io.InputStream input, int maximumBytes) + throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(maximumBytes, 8192)); + byte[] buffer = new byte[8192]; + int total = 0; + while (true) { + int count = input.read(buffer); + if (count < 0) { + return output.toByteArray(); + } + total += count; + if (total > maximumBytes) { + throw new IOException("Kubernetes API response exceeded its bound"); + } + output.write(buffer, 0, count); + } + } + + private static void validateCallBody(ApiCall call, byte[] body) { + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + if (body == null || body.length == 0) { + throw new BindingRejectedException(); + } + try { + JsonNode patch = STRICT_JSON.readTree(decodeUtf8(body)); + JsonNode metadata = patch == null ? null : patch.get("metadata"); + JsonNode data = patch == null ? null : patch.get("data"); + if (patch == null + || !patch.isObject() + || patch.size() != 2 + || metadata == null + || !metadata.isObject() + || metadata.size() != 2 + || !validUid(text(metadata.get("uid"))) + || !validResourceVersion(text(metadata.get("resourceVersion"))) + || data == null + || !data.isObject() + || data.size() != 2 + || !data.has("jwks.json") + || !data.has("jwt-generation.json") + || !data.get("jwks.json").isTextual() + || !data.get("jwt-generation.json").isTextual() + || data.get("jwks.json").asText().isBlank() + || data.get("jwt-generation.json").asText().isBlank()) { + throw new BindingRejectedException(); + } + JsonNode jwks = STRICT_JSON.readTree(data.get("jwks.json").asText()); + JsonNode keys = jwks == null ? null : jwks.get("keys"); + if (jwks == null + || !jwks.isObject() + || jwks.size() != 1 + || keys == null + || !keys.isArray() + || keys.isEmpty()) { + throw new BindingRejectedException(); + } + for (JsonNode key : keys) { + if (!key.isObject() + || key.has("d") + || key.has("p") + || key.has("q") + || key.has("dp") + || key.has("dq") + || key.has("qi") + || key.has("oth") + || key.has("k")) { + throw new BindingRejectedException(); + } + } + } catch (BindingRejectedException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + return; + } + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + String expected = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + if (body == null || !expected.equals(decodeUtf8(body))) { + throw new BindingRejectedException(); + } + return; + } + if (body != null) { + throw new BindingRejectedException(); + } + } + + private static ProtectedFile readProtectedFile(Path path, int maximumBytes) throws IOException { + return readProtectedFile(path, maximumBytes, false); + } + + private static ProtectedFile readBearerProtectedFile(Path configuredPath, Path trustedTokenRoot) + throws IOException { + Path absolute = configuredPath.toAbsolutePath().normalize(); + Path tokenRoot = trustedTokenRoot.toAbsolutePath().normalize(); + if (absolute.getParent() == null + || !absolute.equals(configuredPath) + || !absolute.equals(tokenRoot.resolve("token"))) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Path canonicalTokenRoot = tokenRoot.toRealPath(); + if (!canonicalTokenRoot.equals(tokenRoot) && !canonicalTokenRoot.equals(CANONICAL_TOKEN_ROOT)) { + throw new IOException("Protected Account JWT bearer projection root is invalid"); + } + verifyProtectedDirectory(canonicalTokenRoot); + + BasicFileAttributes linkBefore = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!linkBefore.isSymbolicLink()) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Object linkOwner = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(linkOwner instanceof Number linkUid) || linkUid.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file ownership is invalid"); + } + + Path target = absolute.toRealPath(); + Path versionDirectory = target.getParent(); + Path targetFileName = target.getFileName(); + Path versionDirectoryFileName = + versionDirectory == null ? null : versionDirectory.getFileName(); + if (!target.startsWith(canonicalTokenRoot) + || versionDirectory == null + || !canonicalTokenRoot.equals(versionDirectory.getParent()) + || targetFileName == null + || !"token".equals(targetFileName.toString()) + || versionDirectoryFileName == null + || !versionDirectoryFileName.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw new IOException("Protected Account JWT bearer projection is invalid"); + } + ProtectedFile targetFile = readProtectedFile(target, MAX_BEARER_BYTES, true); + Path targetAfter = absolute.toRealPath(); + BasicFileAttributes linkAfter = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Object linkOwnerAfter = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!target.equals(targetAfter) + || !sameLinkAttributes(linkBefore, linkAfter) + || !(linkOwnerAfter instanceof Number linkUidAfter) + || linkUidAfter.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file changed while reading"); + } + + FileIdentity targetIdentity = targetFile.identity(); + return new ProtectedFile( + targetFile.bytes(), + new FileIdentity( + absolute.toString(), + target + "|link=" + String.valueOf(linkBefore.fileKey()), + targetIdentity.size(), + targetIdentity.modifiedMillis(), + targetIdentity.ownerUid(), + targetIdentity.groupId(), + targetIdentity.permissions(), + targetIdentity.contentSha256())); + } + + private static ProtectedFile readProtectedFile( + Path path, int maximumBytes, boolean bearerCredential) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute) || !absolute.equals(absolute.toRealPath())) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > maximumBytes) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + FileSecurity beforeSecurity = fileSecurity(absolute); + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, beforeSecurity.permissions()); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + FileSecurity afterSecurity = fileSecurity(absolute); + if (!sameAttributes(before, after) || !beforeSecurity.equals(afterSecurity)) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, afterSecurity.permissions()); + } + return new ProtectedFile( + bytes, + new FileIdentity( + absolute.toString(), + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + afterSecurity.ownerUid(), + afterSecurity.groupId(), + afterSecurity.permissions(), + sha256(bytes))); + } + + private static FileSecurity fileSecurity(Path file) throws IOException { + Object owner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(file, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number ownerUid) || !(group instanceof Number groupId)) { + throw new IOException("Protected Account JWT JWKS file ownership is unavailable"); + } + return new FileSecurity( + ownerUid.longValue(), + groupId.longValue(), + Set.copyOf(Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS))); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + verifyProtectedDirectory(parent); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + if (!(fileOwner instanceof Number fileUid) || fileUid.longValue() != 0L || writable(fileMode)) { + throw new IOException("Protected Account JWT JWKS file ownership is invalid"); + } + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + Path normalizedDirectory = directory.toAbsolutePath().normalize(); + Path realDirectory = normalizedDirectory.toRealPath(); + Object directoryOwner = + Files.getAttribute(realDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set directoryMode = + Files.getPosixFilePermissions(realDirectory, LinkOption.NOFOLLOW_LINKS); + if (!realDirectory.equals(normalizedDirectory) + || !Files.isDirectory(realDirectory, LinkOption.NOFOLLOW_LINKS) + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writableByUntrusted(directoryMode)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + } + + private static Path resolveTrustedTokenRoot(ProtectedPaths paths) throws IOException { + Path lexicalRoot = paths.tokenRoot().toAbsolutePath().normalize(); + Path canonicalRoot = lexicalRoot.toRealPath(); + if (paths.testOnly()) { + if (!canonicalRoot.equals(lexicalRoot)) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + } else if (!lexicalRoot.equals(TOKEN_ROOT) + || (!canonicalRoot.equals(TOKEN_ROOT) && !canonicalRoot.equals(CANONICAL_TOKEN_ROOT))) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + return canonicalRoot; + } + + private static void verifyProtectedDirectoryChain(Path directory) throws IOException { + Path normalized = directory.toAbsolutePath().normalize(); + Path canonical = normalized.toRealPath(); + if (!normalized.equals(canonical)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + for (Path current = canonical; current != null; current = current.getParent()) { + verifyProtectedDirectory(current); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean writableByUntrusted(Set permissions) { + return permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static void verifyBearerPermissions(Path file, Set permissions) + throws IOException { + if (!permissions.contains(PosixFilePermission.OWNER_READ) + || !Files.isReadable(file) + || permissions.contains(PosixFilePermission.OTHERS_READ) + || permissions.contains(PosixFilePermission.OWNER_EXECUTE) + || permissions.contains(PosixFilePermission.GROUP_EXECUTE) + || permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) { + throw new IOException("Protected Account JWT bearer file permissions are invalid"); + } + } + + private static boolean validUid(String value) { + return value != null && UID.matcher(value).matches(); + } + + private static boolean validResourceVersion(String value) { + return value != null && value.matches("[!-~]{1,256}"); + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean sameLinkAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return before.isSymbolicLink() == after.isSymbolicLink() + && before.isRegularFile() == after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static String requiredText(JsonNode object, String field, int maximumLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.asText().isEmpty() + || value.asText().length() > maximumLength) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + return value.asText(); + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static URI parseApiServer(String value) { + try { + URI uri = URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() < 1 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (uri.getRawPath() != null + && !uri.getRawPath().isEmpty() + && !"/".equals(uri.getRawPath()))) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + return URI.create("https://" + uri.getRawAuthority() + "/"); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + } + + private static String canonicalDnsName(String value) { + if (value == null || value.isBlank() || value.endsWith(".")) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + try { + String ascii = + IDN.toASCII(value, IDN.USE_STD3_ASCII_RULES).toLowerCase(java.util.Locale.ROOT); + if (ascii.length() > 253 || ascii.startsWith("[") || isIpLiteral(ascii)) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + return ascii; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + } + + private static boolean isIpLiteral(String value) { + return value.matches("[0-9.]+") || value.indexOf(':') >= 0; + } + + private static Path absoluteProtectedPath(String value) { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.normalize().equals(path)) { + throw new IllegalArgumentException("Account JWT JWKS protected path is malformed"); + } + return path; + } + + private static String canonicalUid(String value) { + if (!UID.matcher(value).matches() || "00000000-0000-0000-0000-000000000000".equals(value)) { + throw new IllegalArgumentException("Account JWT JWKS API UID is malformed"); + } + return value; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("Account JWT JWKS protected file is not UTF-8"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw new IllegalStateException("Account JWT JWKS digest is unavailable"); + } + } + + private static FileIdentity testFileIdentity( + String path, byte[] bytes, Set permissions) { + return new FileIdentity( + path, "test-file-identity:" + path, bytes.length, 1L, 0L, 0L, permissions, sha256(bytes)); + } + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + private record FileSecurity(long ownerUid, long groupId, Set permissions) {} + + private record ProtectedState( + ParsedBinding config, + byte[] caBytes, + String bearerToken, + TrustIdentity identity, + FileIdentity bearerIdentity) {} + + private record TrustIdentity( + FileIdentity binding, + FileIdentity ca, + CredentialPolicyIdentity bearer, + String bindingDigest, + String bearerRootRealPath) {} + + private record CredentialPolicyIdentity( + String path, long ownerUid, long groupId, Set permissions) {} + + private record ProtectedPaths( + Path trustRoot, + Path bindingPath, + Path caPath, + Path tokenRoot, + Path tokenPath, + boolean testOnly) {} + + private record FileIdentity( + String path, + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + public record ParsedBinding( + String configRevision, + String environmentId, + String clusterId, + URI apiServer, + String tlsServerName, + Path servingCaPath, + String servingCaSha256, + Path bearerTokenPath, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedApiUsername, + String bindingDigest) {} + + /** One operation-scoped credential lease; all its API calls use the same bearer snapshot. */ + public final class ApiOperation implements AutoCloseable { + private ProtectedState credentialSnapshot; + + private ApiOperation(ProtectedState credentialSnapshot) { + this.credentialSnapshot = credentialSnapshot; + } + + public ParsedBinding binding() { + if (credentialSnapshot == null) { + throw new BindingRejectedException(); + } + return credentialSnapshot.config(); + } + + public ApiResponse send(ApiCall call, byte[] requestBody) { + return AccountJwtJwksApiBinding.this.send(credentialSnapshot, call, requestBody); + } + + /** Reads one Deployment named by the independently protected validator inventory only. */ + public ApiResponse readValidatorDeployment( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.READ_VALIDATOR_DEPLOYMENT, inventory, validator, null); + } + + /** Lists Pods only by the protected validator selector in the pinned namespace. */ + public ApiResponse listValidatorPods( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.LIST_VALIDATOR_PODS, inventory, validator, continuationToken); + } + + /** Reads one ReplicaSet named by an observed Pod owner reference in the pinned namespace. */ + public ApiResponse readValidatorReplicaSet( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String replicaSetName) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, + ApiCall.READ_VALIDATOR_REPLICA_SET, + inventory, + validator, + null, + replicaSetName); + } + + @Override + public void close() { + credentialSnapshot = null; + } + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return sendInventoryRead( + credentialSnapshot, call, inventory, validator, continuationToken, null); + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken, + String replicaSetName) { + if (credentialSnapshot == null + || inventory == null + || validator == null + || !inventory.matchesApiBinding(credentialSnapshot.config()) + || inventory.validators().stream().noneMatch(expected -> expected == validator)) { + throw new BindingRejectedException(); + } + String path; + if (call == ApiCall.READ_VALIDATOR_DEPLOYMENT) { + if (continuationToken != null) { + throw new BindingRejectedException(); + } + path = + "/apis/apps/v1/namespaces/" + + inventory.namespace() + + "/deployments/" + + validator.deploymentName(); + } else if (call == ApiCall.LIST_VALIDATOR_PODS) { + String selector = + validator.selector().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(java.util.stream.Collectors.joining(",")); + path = + "/api/v1/namespaces/" + + inventory.namespace() + + "/pods?labelSelector=" + + queryEncode(selector) + + "&limit=250"; + if (continuationToken != null && !continuationToken.isEmpty()) { + if (continuationToken.length() > 2048 + || !continuationToken.matches("[A-Za-z0-9_./+=-]{1,2048}")) { + throw new BindingRejectedException(); + } + path += "&continue=" + queryEncode(continuationToken); + } + } else if (call == ApiCall.READ_VALIDATOR_REPLICA_SET) { + if (continuationToken != null + || replicaSetName == null + || !replicaSetName.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new BindingRejectedException(); + } + path = "/apis/apps/v1/namespaces/" + inventory.namespace() + "/replicasets/" + replicaSetName; + } else { + throw new BindingRejectedException(); + } + return send(credentialSnapshot, call, null, path); + } + + private static String queryEncode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); + } + + public enum ApiCall { + REVIEW_AUTHENTICATED_PRINCIPAL("POST", "/apis/authentication.k8s.io/v1/selfsubjectreviews"), + READ_KUBE_SYSTEM_NAMESPACE("GET", "/api/v1/namespaces/kube-system"), + READ_TARGET_NAMESPACE("GET", null), + READ_JWKS_CONFIG_MAP("GET", null), + PATCH_JWKS_CONFIG_MAP("PATCH", null), + READ_VALIDATOR_DEPLOYMENT("GET", null), + LIST_VALIDATOR_PODS("GET", null), + READ_VALIDATOR_REPLICA_SET("GET", null); + + private final String method; + private final String fixedPath; + + ApiCall(String method, String fixedPath) { + this.method = method; + this.fixedPath = fixedPath; + } + + public String method() { + return method; + } + + private String path(String namespace) { + return switch (this) { + case REVIEW_AUTHENTICATED_PRINCIPAL, READ_KUBE_SYSTEM_NAMESPACE -> fixedPath; + case READ_TARGET_NAMESPACE -> "/api/v1/namespaces/" + namespace; + case READ_JWKS_CONFIG_MAP, PATCH_JWKS_CONFIG_MAP -> + "/api/v1/namespaces/" + namespace + "/configmaps/jwt-jwks"; + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new BindingRejectedException(); + }; + } + } + + public record ApiResponse(int statusCode, byte[] body) { + public ApiResponse { + body = body == null ? new byte[0] : body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + } + + public static final class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account JWT JWKS API binding is unavailable or changed"); + } + } + + public static final class ApiTransportException extends RuntimeException { + public ApiTransportException() { + super("Account JWT JWKS Kubernetes API request failed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java new file mode 100644 index 0000000000..ecd37c379a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java @@ -0,0 +1,480 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collection; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** Independently protected, expiring trust for the non-authorizing readiness RPC only. */ +@Component +public final class AccountJwtReadinessTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-readiness-trust-binding/v1"; + private static final String VALIDATOR_ID = "account-service"; + private static final String HARNESS_SERVICE_ACCOUNT = "account-jwt-readiness-harness"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "validatorId", + "validatorInstanceId", + "validUntilEpochSecond", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern INSTANCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + private final Clock clock; + + @Autowired + public AccountJwtReadinessTrustBinding( + @Value("${firemud.account.jwt-readiness.validation.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-readiness.validation.protected-binding-path:}") + String protectedBindingPath) { + this(enabled, protectedBindingPath, Clock.systemUTC()); + } + + AccountJwtReadinessTrustBinding(boolean enabled, String protectedBindingPath, Clock clock) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.clock = Objects.requireNonNull(clock); + } + + /** Missing, disabled, malformed, expired, or mutable trust configuration denies access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath), clock.instant())); + } catch (Exception ex) { + return Optional.empty(); + } + } + + static Binding parseProtectedBytes(byte[] bytes, long nowEpochSecond) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw unavailable(); + } + Map fields = parseFields(decodeUtf8(bytes)); + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw unavailable(); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + String instanceId = fields.get("validatorInstanceId"); + long validUntil = parsePositiveLong(fields.get("validUntilEpochSecond")); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches() + || !INSTANCE.matcher(instanceId).matches() + || !VALIDATOR_ID.equals(fields.get("validatorId")) + || nowEpochSecond <= 0L + || nowEpochSecond >= validUntil) { + throw unavailable(); + } + + String expectedUri = fields.get("expectedPeerUri"); + if (!expectedHarnessUri(namespace, expectedUri)) { + throw unavailable(); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + instanceId, + validUntil); + if (!digest.equals(fields.get("bindingDigest"))) { + throw unavailable(); + } + return new Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + VALIDATOR_ID, + instanceId, + validUntil, + digest); + } + + private static Binding readProtectedFile(Path path, java.time.Instant now) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected readiness binding is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected readiness binding is unavailable"); + } + verifyRootOwnedAndNonWritable(absolute); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected readiness binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes, now.getEpochSecond()); + } + + private static Map parseFields(String text) { + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw unavailable(); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw unavailable(); + } + } + return fields; + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected readiness binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected readiness binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw unavailable(); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw unavailable(); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw unavailable(); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean expectedHarnessUri(String namespace, String uri) { + return ("spiffe://firemud/ns/" + namespace + "/sa/" + HARNESS_SERVICE_ACCOUNT).equals(uri); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw unavailable(); + } + return uuid.toString(); + } + + private static long parsePositiveLong(String value) { + try { + long result = Long.parseLong(value); + if (result <= 0L || !Long.toString(result).equals(value)) { + throw unavailable(); + } + return result; + } catch (NumberFormatException ex) { + throw unavailable(); + } + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins, + String validatorInstanceId, + long validUntilEpochSecond) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + binding.put("validatorId", VALIDATOR_ID); + binding.put("validatorInstanceId", validatorInstanceId); + binding.put("validUntilEpochSecond", validUntilEpochSecond); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalStateException("Readiness binding digest is unavailable"); + } + } + + public static PeerIdentity identifyPeer(java.security.cert.Certificate[] certificates) { + if (certificates == null || certificates.length == 0) { + throw new PeerIdentityRejectedException(); + } + if (!(certificates[0] instanceof X509Certificate certificate)) { + throw new PeerIdentityRejectedException(); + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + throw new PeerIdentityRejectedException(); + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + throw new PeerIdentityRejectedException(); + } + foundUri = uri; + } + if (uriCount != 1 || foundUri == null) { + throw new PeerIdentityRejectedException(); + } + String spki = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(certificate.getPublicKey().getEncoded())); + return new PeerIdentity(foundUri, spki); + } catch (CertificateException | NoSuchAlgorithmException ex) { + throw new PeerIdentityRejectedException(); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Readiness trust binding is unavailable"); + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] certificates, Binding binding) { + if (binding == null) { + return false; + } + try { + PeerIdentity peer = identifyPeer(certificates); + return binding.matches(peer); + } catch (RuntimeException rejected) { + return false; + } + } + + public record PeerIdentity(String uri, String spkiSha256) {} + + /** + * Configured per-validator-instance identity; this is not proof of pod UID or fleet inventory. + */ + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String validatorId, + String validatorInstanceId, + long validUntilEpochSecond, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(namespace); + Objects.requireNonNull(expectedClusterIncarnationUid); + Objects.requireNonNull(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + Objects.requireNonNull(configRevision); + Objects.requireNonNull(validatorInstanceId); + Objects.requireNonNull(bindingDigest); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(configRevision).matches() + || !INSTANCE.matcher(validatorInstanceId).matches() + || !VALIDATOR_ID.equals(validatorId) + || peerSpkiSha256Pins.isEmpty() + || peerSpkiSha256Pins.size() > 8 + || validUntilEpochSecond <= 0L + || !SHA256.matcher(bindingDigest).matches() + || !expectedHarnessUri(namespace, expectedPeerUri) + || !peerSpkiSha256Pins.stream().allMatch(pin -> SHA256.matcher(pin).matches()) + || peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw unavailable(); + } + UUID clusterUid = UUID.fromString(expectedClusterIncarnationUid); + UUID namespaceUid = UUID.fromString(expectedNamespaceUid); + if (!clusterUid.toString().equals(expectedClusterIncarnationUid) + || !namespaceUid.toString().equals(expectedNamespaceUid) + || clusterUid.equals(new UUID(0L, 0L)) + || namespaceUid.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins, + validatorInstanceId, + validUntilEpochSecond); + if (!expectedDigest.equals(bindingDigest)) { + throw unavailable(); + } + } + + public boolean isCurrentAt(long nowEpochSecond) { + return nowEpochSecond > 0L && nowEpochSecond < validUntilEpochSecond; + } + + public boolean matches(PeerIdentity peer) { + if (peer == null || !expectedPeerUri.equals(peer.uri())) { + return false; + } + try { + byte[] actual = HexFormat.of().parseHex(peer.spkiSha256()); + boolean matched = false; + for (String pin : peerSpkiSha256Pins) { + matched |= MessageDigest.isEqual(actual, HexFormat.of().parseHex(pin)); + } + return matched; + } catch (IllegalArgumentException malformedPeer) { + return false; + } + } + } + + public static final class PeerIdentityRejectedException extends RuntimeException { + public PeerIdentityRejectedException() { + super("Readiness caller identity is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java new file mode 100644 index 0000000000..71ba3c2455 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reads the independently protected trust binding for Account's narrow JWT materializer RPCs. The + * file must be root-owned and non-writable by the Account/materializer workload. It is read again + * for every RPC so pin rotation or trust withdrawal takes effect without process restart. + */ +@Component +public final class AccountJwtSignerMaterializerTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-signer-materializer-binding/v1"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + + public AccountJwtSignerMaterializerTrustBinding( + @Value("${firemud.account.jwt-signer.materialization.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-signer.materialization.protected-binding-path:}") + String protectedBindingPath) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + } + + /** Missing, disabled, malformed, or mutable trust configuration always means no access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath))); + } catch (Exception ex) { + // Never expose config contents, file paths, or certificate details through RPC errors. + return Optional.empty(); + } + } + + /** Testable parser boundary; production calls still require the protected-file checks above. */ + static AccountJwtSignerMaterializerTrustBinding.Binding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw new IllegalArgumentException("JWT materializer trust binding is unavailable"); + } + String text = decodeUtf8(bytes); + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + } + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw new IllegalArgumentException("JWT materializer trust binding is disabled"); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String expectedUri = fields.get("expectedPeerUri"); + if (!validExpectedPeerUri(namespace, expectedUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins); + if (!digest.equals(fields.get("bindingDigest"))) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + return new AccountJwtSignerMaterializerTrustBinding.Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + digest); + } + + private static Binding readProtectedFile(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile()) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + verifyRootOwnedAndNonWritable(absolute); + if (before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected Account JWT materializer binding size is invalid"); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT materializer binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected Account JWT materializer binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("JWT materializer trust binding is not UTF-8", ex); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean validExpectedPeerUri(String namespace, String uri) { + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + return uri != null + && uri.startsWith(prefix) + && ENVIRONMENT.matcher(uri.substring(prefix.length())).matches(); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw new IllegalArgumentException("JWT materializer trust UID is malformed"); + } + return uuid.toString(); + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (Exception ex) { + throw new IllegalStateException("JWT materializer trust binding digest is unavailable", ex); + } + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] peerCertificates, Binding binding) { + if (peerCertificates == null || peerCertificates.length == 0 || binding == null) { + return false; + } + if (!(peerCertificates[0] instanceof X509Certificate certificate)) { + return false; + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + return false; + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + return false; + } + foundUri = uri; + } + if (uriCount != 1 || !binding.expectedPeerUri().equals(foundUri)) { + return false; + } + byte[] spkiDigest = + MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded()); + byte[] configuredPin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(0)); + boolean matched = MessageDigest.isEqual(spkiDigest, configuredPin); + for (int index = 1; index < binding.peerSpkiSha256Pins().size(); index++) { + byte[] pin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(index)); + matched |= MessageDigest.isEqual(spkiDigest, pin); + } + return matched; + } catch (CertificateException | NoSuchAlgorithmException | RuntimeException ex) { + return false; + } + } + + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId, "Environment identity is required"); + Objects.requireNonNull(clusterId, "Cluster identity is required"); + Objects.requireNonNull(namespace, "Namespace identity is required"); + canonicalUuid(expectedClusterIncarnationUid); + canonicalUuid(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri, "Materializer URI identity is required"); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + if (peerSpkiSha256Pins.isEmpty() || peerSpkiSha256Pins.size() > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are unavailable"); + } + for (String pin : peerSpkiSha256Pins) { + if (!SHA256.matcher(pin).matches()) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + } + Objects.requireNonNull(configRevision, "Materializer trust revision is required"); + if (!REVISION.matcher(configRevision).matches() || !SHA256.matcher(bindingDigest).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding digest is malformed"); + } + if (peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw new IllegalArgumentException("JWT materializer certificate pins are duplicated"); + } + AccountJwtSignerDesiredStateRepository.Binding stateBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + if (!validExpectedPeerUri(stateBinding.namespace(), expectedPeerUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins); + if (!expectedDigest.equals(bindingDigest)) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + } + + public AccountJwtSignerDesiredStateRepository.Binding accountBinding() { + return new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java new file mode 100644 index 0000000000..6f775620ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -0,0 +1,842 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +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; + +/** + * Default-inactive, independently protected expected validator applicability and runtime pins. + * + *

This binding is an operator-installed input, never learned from Kubernetes labels, caller + * claims, a first read, or the readiness plan's partial applicability matrix. It provides no + * readiness, promotion, or per-validator acceptance authority. + */ +public final class AccountJwtValidatorInventoryBinding { + public static final int MAX_BINDING_BYTES = 32 * 1024; + public static final int MAX_RUNTIME_CONFIG_BYTES = 8 * 1024; + public static final Path PROTECTED_BINDING_PATH = + Path.of("/etc/firemud/account-jwt-api/validator-inventory.json"); + private static final Path PROTECTED_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final String VERSION = "account-jwt-validator-inventory-binding/v2"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Set ROOT_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "apiBindingRevision", + "apiBindingDigest", + "validators", + "bindingDigest"); + private static final Set VALIDATOR_FIELDS = + Set.of( + "validatorId", + "deploymentName", + "deploymentUid", + "selector", + "replicas", + "containerName", + "image", + "jwksUri", + "maxCacheAgeSeconds", + "profiles", + "receiverServiceUri", + "receiverPort", + "receiverPods"); + private static final Set PROFILE_FIELDS = Set.of("tokenProfile", "audience"); + private static final Set RECEIVER_POD_FIELDS = + Set.of("podUid", "podIp", "leafSpkiSha256"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Pattern DNS_LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern ENVIRONMENT = DNS_LABEL; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = CLUSTER; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern LABEL_KEY = + Pattern.compile( + "[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?(?:/[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern LABEL_VALUE = + Pattern.compile("(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,63}"); + private static final Pattern AUDIENCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}"); + private static final Pattern RECEIVER_SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + private final boolean enabled; + private final String configuredPath; + private final AtomicReference acceptedFile = new AtomicReference<>(); + + /** Creates a disabled binding; production composition must opt in with the one fixed path. */ + public AccountJwtValidatorInventoryBinding() { + this(false, ""); + } + + public AccountJwtValidatorInventoryBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String path = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.configuredPath = PROTECTED_BINDING_PATH.toString().equals(path) ? path : ""; + } + + /** Returns the exact immutable protected expectations, or empty when disabled/unavailable. */ + public java.util.Optional current() { + if (!enabled || configuredPath.isBlank()) { + return java.util.Optional.empty(); + } + try { + ProtectedFile file = readProtectedFile(PROTECTED_BINDING_PATH); + ProtectedInventory parsed = parseProtectedBytes(file.bytes()); + FileIdentity existing = acceptedFile.get(); + if (existing == null) { + acceptedFile.compareAndSet(null, file.identity()); + existing = acceptedFile.get(); + } + if (!file.identity().equals(existing)) { + throw unavailable(); + } + return java.util.Optional.of(parsed); + } catch (RuntimeException | IOException failure) { + return java.util.Optional.empty(); + } + } + + static ProtectedInventory parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw unavailable(); + } + try { + JsonNode root = JSON.readTree(decodeUtf8(bytes)); + requireObjectFields(root, ROOT_FIELDS); + if (!VERSION.equals(requiredText(root, "version", 96)) + || !"true".equals(requiredText(root, "enabled", 5))) { + throw unavailable(); + } + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiRevision = requiredText(root, "apiBindingRevision", 128); + String apiDigest = requiredText(root, "apiBindingDigest", 64); + String digest = requiredText(root, "bindingDigest", 64); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !DNS_LABEL.matcher(namespace).matches() + || !REVISION.matcher(apiRevision).matches() + || !SHA256.matcher(apiDigest).matches() + || !SHA256.matcher(digest).matches() + || !digest.equals(computeBindingDigest(root))) { + throw unavailable(); + } + List validators = parseValidators(root.get("validators")); + if (validators.isEmpty() || validators.size() > 32) { + throw unavailable(); + } + return new ProtectedInventory( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + apiRevision, + apiDigest, + digest, + validators); + } catch (IllegalArgumentException failure) { + throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + public static String computeBindingDigest(JsonNode root) { + try { + requireObjectFields(root, ROOT_FIELDS); + Map value = new LinkedHashMap<>(); + for (String field : ROOT_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode node = root.get(field); + value.put(field, JSON.readValue(JSON.writeValueAsString(node), Object.class)); + } + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException failure) { + throw unavailable(); + } + } + + private static List parseValidators(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List result = new ArrayList<>(); + Set ids = new LinkedHashSet<>(); + Set deployments = new LinkedHashSet<>(); + Set expectedPodUids = new LinkedHashSet<>(); + Set expectedPodIps = new LinkedHashSet<>(); + Set expectedPodSpkis = new LinkedHashSet<>(); + for (JsonNode validator : node) { + requireObjectFields(validator, VALIDATOR_FIELDS); + String id = requiredText(validator, "validatorId", 63); + String deployment = requiredText(validator, "deploymentName", 63); + String deploymentUid = canonicalUid(requiredText(validator, "deploymentUid", 36)); + String container = requiredText(validator, "containerName", 63); + String image = requiredText(validator, "image", 512); + String jwksUri = canonicalJwksUri(requiredText(validator, "jwksUri", 512)); + int replicas = exactInt(validator.get("replicas"), 1, 128); + int maximumCacheAge = exactInt(validator.get("maxCacheAgeSeconds"), 1, 300); + if (!DNS_LABEL.matcher(id).matches() + || !DNS_LABEL.matcher(deployment).matches() + || !DNS_LABEL.matcher(container).matches() + || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}") + || !ids.add(id) + || !deployments.add(deployment)) { + throw unavailable(); + } + Map selector = parseSelector(validator.get("selector")); + List profiles = parseProfiles(validator.get("profiles")); + if (profiles.isEmpty()) { + throw unavailable(); + } + List receiverPods = + parseReceiverPods(validator.get("receiverPods"), replicas); + for (ReceiverPodPin pin : receiverPods) { + // Validator workloads are distinct expected instances in this closed LOGIN matrix. A + // shared leaf key would make the TLS peer prove only possession by either Pod, not the + // exact Pod UID selected by the owner-observed inventory. + if (!expectedPodUids.add(pin.podUid()) + || !expectedPodIps.add(pin.podIp()) + || !expectedPodSpkis.add(pin.leafSpkiSha256())) { + throw unavailable(); + } + } + String runtimeConfig = canonicalRuntimeConfig(jwksUri, maximumCacheAge, profiles); + if (runtimeConfig.getBytes(StandardCharsets.UTF_8).length > MAX_RUNTIME_CONFIG_BYTES) { + throw unavailable(); + } + result.add( + new ValidatorExpectation( + id, + deployment, + deploymentUid, + selector, + replicas, + container, + image, + jwksUri, + maximumCacheAge, + profiles, + runtimeConfig, + canonicalReceiverServiceUri(requiredText(validator, "receiverServiceUri", 256)), + exactInt(validator.get("receiverPort"), 1, 65535), + receiverPods)); + } + return List.copyOf(result); + } + + private static List parseReceiverPods(JsonNode node, int replicas) { + if (node == null || !node.isArray() || node.size() != replicas || node.size() > 128) { + throw unavailable(); + } + List pins = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podIps = new LinkedHashSet<>(); + Set podSpkis = new LinkedHashSet<>(); + String previousUid = null; + for (JsonNode pod : node) { + requireObjectFields(pod, RECEIVER_POD_FIELDS); + String uid = canonicalUid(requiredText(pod, "podUid", 36)); + String ip = canonicalPodIp(requiredText(pod, "podIp", 45)); + String spki = requiredText(pod, "leafSpkiSha256", 64); + if (!SHA256.matcher(spki).matches() + || !podUids.add(uid) + || !podIps.add(ip) + || !podSpkis.add(spki) + || (previousUid != null && previousUid.compareTo(uid) >= 0)) { + throw unavailable(); + } + previousUid = uid; + pins.add(new ReceiverPodPin(uid, ip, spki)); + } + return List.copyOf(pins); + } + + private static String canonicalReceiverServiceUri(String value) { + if (!RECEIVER_SERVICE_URI.matcher(value).matches()) { + throw unavailable(); + } + return value; + } + + public static String canonicalPodIp(String value) { + if (value == null || value.isBlank() || value.indexOf('%') >= 0) { + throw unavailable(); + } + try { + if (value.indexOf(':') < 0) { + String[] components = value.split("\\.", -1); + if (components.length != 4) { + throw unavailable(); + } + for (String component : components) { + if (component.isEmpty() + || (component.length() > 1 && component.charAt(0) == '0') + || !component.matches("[0-9]{1,3}") + || Integer.parseInt(component) > 255) { + throw unavailable(); + } + } + if ("0.0.0.0".equals(value) || "255.255.255.255".equals(value)) { + throw unavailable(); + } + return value; + } + if (!value.matches("[0-9A-Fa-f:]+")) { + throw unavailable(); + } + InetAddress address = InetAddress.getByName(value); + if (!(address instanceof Inet6Address) + || !canonicalIpv6(address.getAddress()).equals(value)) { + throw unavailable(); + } + return value; + } catch (IOException | NumberFormatException failure) { + throw unavailable(); + } + } + + private static String canonicalIpv6(byte[] bytes) { + if (bytes.length != 16) { + throw unavailable(); + } + int[] groups = new int[8]; + for (int index = 0; index < groups.length; index++) { + groups[index] = + Byte.toUnsignedInt(bytes[index * 2]) << 8 | Byte.toUnsignedInt(bytes[index * 2 + 1]); + } + int bestStart = -1; + int bestLength = 1; + for (int index = 0; index < groups.length; ) { + if (groups[index] != 0) { + index++; + continue; + } + int end = index; + while (end < groups.length && groups[end] == 0) { + end++; + } + if (end - index > bestLength) { + bestStart = index; + bestLength = end - index; + } + index = end; + } + StringBuilder canonical = new StringBuilder(); + for (int index = 0; index < groups.length; ) { + if (index == bestStart) { + canonical.append("::"); + index += bestLength; + continue; + } + if (canonical.length() > 0 && canonical.charAt(canonical.length() - 1) != ':') { + canonical.append(':'); + } + canonical.append(Integer.toHexString(groups[index])); + index++; + } + return canonical.toString(); + } + + private static Map parseSelector(JsonNode node) { + if (node == null || !node.isObject() || node.isEmpty() || node.size() > 16) { + throw unavailable(); + } + Map selector = new LinkedHashMap<>(); + for (Map.Entry entry : node.properties()) { + if (!LABEL_KEY.matcher(entry.getKey()).matches() + || !entry.getValue().isTextual() + || !LABEL_VALUE.matcher(entry.getValue().asText()).matches()) { + throw unavailable(); + } + selector.put(entry.getKey(), entry.getValue().asText()); + } + return Map.copyOf(selector); + } + + private static List parseProfiles(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List profiles = new ArrayList<>(); + Set unique = new LinkedHashSet<>(); + for (JsonNode profile : node) { + requireObjectFields(profile, PROFILE_FIELDS); + String name = requiredText(profile, "tokenProfile", 64); + String audience = requiredText(profile, "audience", 256); + if (!PROFILE.matcher(name).matches() + || !AUDIENCE.matcher(audience).matches() + || !unique.add(name + "\u0000" + audience)) { + throw unavailable(); + } + profiles.add(new ProfileExpectation(name, audience)); + } + profiles.sort( + Comparator.comparing(ProfileExpectation::tokenProfile) + .thenComparing(ProfileExpectation::audience)); + return List.copyOf(profiles); + } + + private static String canonicalRuntimeConfig( + String jwksUri, int maxCacheAgeSeconds, List profiles) { + try { + List> profileValues = + profiles.stream() + .map( + profile -> + Map.of( + "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList(); + Map runtime = + Map.of( + "algorithm", + "RS256", + "jwksUri", + jwksUri, + "maxCacheAgeSeconds", + maxCacheAgeSeconds, + "profiles", + profileValues); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(runtime)), + StandardCharsets.UTF_8); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static String canonicalJwksUri(String value) { + try { + java.net.URI uri = java.net.URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !"/.well-known/jwks.json".equals(uri.getRawPath())) { + throw unavailable(); + } + return uri.toASCIIString(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static ProtectedFile readProtectedFile(Path path) throws IOException { + if (!path.equals(PROTECTED_BINDING_PATH) + || Files.isSymbolicLink(path) + || !path.equals(path.toRealPath())) { + throw unavailable(); + } + verifyProtectedDirectory(PROTECTED_ROOT); + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || before.size() <= 0 + || before.size() > MAX_BINDING_BYTES + || !(owner instanceof Number uid) + || uid.longValue() != 0L + || !(group instanceof Number gid) + || writable(mode) + || !mode.contains(PosixFilePermission.OWNER_READ) + || mode.contains(PosixFilePermission.OTHERS_READ)) { + throw unavailable(); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set afterMode = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object afterOwner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object afterGroup = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!sameAttributes(before, after) + || !mode.equals(afterMode) + || !Objects.equals(owner, afterOwner) + || !Objects.equals(group, afterGroup)) { + throw unavailable(); + } + FileIdentity identity = + new FileIdentity( + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + uid.longValue(), + gid.longValue(), + Set.copyOf(mode), + sha256(bytes)); + return new ProtectedFile(bytes, identity); + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + if (!directory.equals(directory.toRealPath()) + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + Object owner = Files.getAttribute(directory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) + || uid.longValue() != 0L + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + throw unavailable(); + } + } + + private static void requireObjectFields(JsonNode node, Set expected) { + if (node == null || !node.isObject() || node.size() != expected.size()) { + throw unavailable(); + } + for (Map.Entry field : node.properties()) { + if (!expected.contains(field.getKey()) + || field.getValue() == null + || field.getValue().isNull()) { + throw unavailable(); + } + } + } + + private static String requiredText(JsonNode node, String field, int maximumLength) { + JsonNode value = node.get(field); + if (value == null + || !value.isTextual() + || value.asText().isBlank() + || value.asText().length() > maximumLength) { + throw unavailable(); + } + return value.asText(); + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToInt()) { + throw unavailable(); + } + int value = node.intValue(); + if (value < minimum || value > maximum) { + throw unavailable(); + } + return value; + } + + private static String canonicalUid(String uid) { + if (!UID.matcher(uid).matches() || uid.startsWith("00000000-")) { + throw unavailable(); + } + return uid; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean writable(Set mode) { + return mode.contains(PosixFilePermission.OWNER_WRITE) + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Protected Account validator inventory binding is unavailable"); + } + + private record FileIdentity( + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + /** An immutable, file-backed expected inventory; no public constructor or mutation exists. */ + public static final class ProtectedInventory { + private final String configRevision; + private final String environmentId; + private final String clusterId; + private final String namespace; + private final String expectedClusterIncarnationUid; + private final String expectedNamespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String bindingDigest; + private final List validators; + + private ProtectedInventory( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String bindingDigest, + List validators) { + this.configRevision = configRevision; + this.environmentId = environmentId; + this.clusterId = clusterId; + this.namespace = namespace; + this.expectedClusterIncarnationUid = expectedClusterIncarnationUid; + this.expectedNamespaceUid = expectedNamespaceUid; + this.apiBindingRevision = apiBindingRevision; + this.apiBindingDigest = apiBindingDigest; + this.bindingDigest = bindingDigest; + this.validators = List.copyOf(validators); + } + + public boolean matchesApiBinding(AccountJwtJwksApiBinding.ParsedBinding binding) { + return binding != null + && configRevision != null + && environmentId.equals(binding.environmentId()) + && clusterId.equals(binding.clusterId()) + && namespace.equals(binding.namespace()) + && expectedClusterIncarnationUid.equals(binding.expectedClusterIncarnationUid()) + && expectedNamespaceUid.equals(binding.expectedNamespaceUid()) + && apiBindingRevision.equals(binding.configRevision()) + && apiBindingDigest.equals(binding.bindingDigest()); + } + + public String configRevision() { + return configRevision; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String namespace() { + return namespace; + } + + public String expectedClusterIncarnationUid() { + return expectedClusterIncarnationUid; + } + + public String expectedNamespaceUid() { + return expectedNamespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String bindingDigest() { + return bindingDigest; + } + + public List validators() { + return validators; + } + } + + public static final class ValidatorExpectation { + private final String validatorId; + private final String deploymentName; + private final String deploymentUid; + private final Map selector; + private final int replicas; + private final String containerName; + private final String image; + private final String jwksUri; + private final int maxCacheAgeSeconds; + private final List profiles; + private final String canonicalRuntimeConfig; + private final String receiverServiceUri; + private final int receiverPort; + private final List receiverPods; + + private ValidatorExpectation( + String validatorId, + String deploymentName, + String deploymentUid, + Map selector, + int replicas, + String containerName, + String image, + String jwksUri, + int maxCacheAgeSeconds, + List profiles, + String canonicalRuntimeConfig, + String receiverServiceUri, + int receiverPort, + List receiverPods) { + this.validatorId = validatorId; + this.deploymentName = deploymentName; + this.deploymentUid = deploymentUid; + this.selector = Map.copyOf(selector); + this.replicas = replicas; + this.containerName = containerName; + this.image = image; + this.jwksUri = jwksUri; + this.maxCacheAgeSeconds = maxCacheAgeSeconds; + this.profiles = List.copyOf(profiles); + this.canonicalRuntimeConfig = canonicalRuntimeConfig; + this.receiverServiceUri = receiverServiceUri; + this.receiverPort = receiverPort; + this.receiverPods = List.copyOf(receiverPods); + } + + public String validatorId() { + return validatorId; + } + + public String deploymentName() { + return deploymentName; + } + + public String deploymentUid() { + return deploymentUid; + } + + public Map selector() { + return selector; + } + + public int replicas() { + return replicas; + } + + public String containerName() { + return containerName; + } + + public String image() { + return image; + } + + public String jwksUri() { + return jwksUri; + } + + public int maxCacheAgeSeconds() { + return maxCacheAgeSeconds; + } + + public List profiles() { + return profiles; + } + + public String canonicalRuntimeConfig() { + return canonicalRuntimeConfig; + } + + public String receiverServiceUri() { + return receiverServiceUri; + } + + public int receiverPort() { + return receiverPort; + } + + public List receiverPods() { + return receiverPods; + } + } + + public record ReceiverPodPin(String podUid, String podIp, String leafSpkiSha256) {} + + public record ProfileExpectation(String tokenProfile, String audience) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java new file mode 100644 index 0000000000..f12f41ea2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java @@ -0,0 +1,280 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only exact lookup of immutable Account control-ui issuance evidence. */ +@Repository +public class AccountControlUiCommittedIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_CLAIMS = 16 * 1024; + private static final int MAX_SOURCE = 131072; + private static final int MAX_BUNDLE = 131072; + private static final int MAX_SIGNER_RECEIPT = 65536; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring injects the shared transaction-aware DSLContext; this proxyable repository only validates that dependency and acquires no resources in its constructor.") + public AccountControlUiCommittedIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Reads only the exact still-COMMITTED issuance row in the caller's Account transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommitted(String tokenHash) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account issuance read requires an Account transaction"); + } + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + Record row = + dsl.fetchOne( + "SELECT request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status, token_hash, " + + "pending_registry, active_registry, pending_receipt, committed_at, " + + "recovery_failed_at FROM " + + TABLE + + " WHERE token_hash = ? FOR SHARE", + tokenHash); + if (row == null) { + return Optional.empty(); + } + try { + CommittedIssuance evidence = new CommittedIssuance(row); + if (!"COMMITTED".equals(evidence.status()) + || !tokenHash.equals(evidence.tokenHash()) + || evidence.recoveryFailedAt() != null + || evidence.committedAt() == null + || evidence.pendingReceipt().length == 0) { + throw denied(); + } + return Optional.of(evidence); + } catch (RuntimeException malformed) { + throw denied(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact committed Account control-ui issuance evidence unavailable"); + } + + private static byte[] bytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw denied(); + } + return value.clone(); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || isNil(value)) { + throw denied(); + } + return value; + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw denied(); + } + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw denied(); + } + return value; + } + + private static String tokenHash(Record row) { + String value = row.get("token_hash", String.class); + if (value == null || !TOKEN_HASH.matcher(value).matches()) { + throw denied(); + } + return value; + } + + /** Defensive immutable owner row; it does not contain the compact JWT or response envelope. */ + public static final class CommittedIssuance { + private final UUID requestId; + private final UUID operationId; + private final UUID tokenJti; + private final UUID accountId; + private final UUID tenantId; + private final String callerWorkload; + private final UUID callerContextId; + private final String requestDigest; + private final byte[] claims; + private final byte[] source; + private final byte[] bundle; + private final byte[] signerReceipt; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String status; + private final String tokenHash; + private final byte[] pendingRegistry; + private final byte[] activeRegistry; + private final byte[] pendingReceipt; + private final java.time.OffsetDateTime committedAt; + private final java.time.OffsetDateTime recoveryFailedAt; + + private CommittedIssuance(Record row) { + requestId = uuid(row, "request_id"); + operationId = uuid(row, "operation_id"); + tokenJti = uuid(row, "token_jti"); + accountId = uuid(row, "account_uuid"); + tenantId = uuid(row, "tenant_uuid"); + callerWorkload = text(row, "caller_workload"); + callerContextId = uuid(row, "caller_context_id"); + requestDigest = digest(row, "request_digest"); + claims = bytes(row, "claims_payload", MAX_CLAIMS); + source = bytes(row, "source_payload", MAX_SOURCE); + bundle = bytes(row, "bundle_payload", MAX_BUNDLE); + signerReceipt = bytes(row, "signer_receipt", MAX_SIGNER_RECEIPT); + issuedAtEpochSecond = positive(row, "issued_at_epoch_second"); + expiresAtEpochSecond = positive(row, "expires_at_epoch_second"); + if (expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw denied(); + } + status = text(row, "status"); + tokenHash = AccountControlUiCommittedIssuanceRepository.tokenHash(row); + pendingRegistry = bytes(row, "pending_registry", 32768); + activeRegistry = bytes(row, "active_registry", 32768); + pendingReceipt = bytes(row, "pending_receipt", 8192); + committedAt = row.get("committed_at", java.time.OffsetDateTime.class); + recoveryFailedAt = row.get("recovery_failed_at", java.time.OffsetDateTime.class); + } + + private static String digest(Record row, String field) { + String value = text(row, field); + if (!Pattern.matches("[0-9a-f]{64}", value)) { + throw denied(); + } + return value; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return operationId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public String callerWorkload() { + return callerWorkload; + } + + public UUID callerContextId() { + return callerContextId; + } + + public String requestDigest() { + return requestDigest; + } + + public byte[] claims() { + return claims.clone(); + } + + public byte[] source() { + return source.clone(); + } + + public byte[] bundle() { + return bundle.clone(); + } + + public byte[] signerReceipt() { + return signerReceipt.clone(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String status() { + return status; + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] pendingRegistry() { + return pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return activeRegistry.clone(); + } + + public byte[] pendingReceipt() { + return pendingReceipt.clone(); + } + + public java.time.OffsetDateTime committedAt() { + return committedAt; + } + + public java.time.OffsetDateTime recoveryFailedAt() { + return recoveryFailedAt; + } + + public long expiryMillis() { + try { + return Math.multiplyExact(expiresAtEpochSecond, 1000L); + } catch (ArithmeticException malformed) { + throw denied(); + } + } + + @Override + public String toString() { + return "AccountControlUiCommittedIssuanceRepository.CommittedIssuance[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java new file mode 100644 index 0000000000..fb05ddfa81 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable pending-issuance identity data; this value is not signing or authorization evidence. + */ +public record AccountGameplayDelegationPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayDelegationPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(tokenJti); + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("Request digest is malformed"); + } + if (callerWorkload == null || callerWorkload.length() > 256) { + throw new IllegalArgumentException("Caller workload is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java new file mode 100644 index 0000000000..c76f1951e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -0,0 +1,1315 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +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.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account-owned evidence for the fixed public JWT ConfigMap projection. + * + *

Every write re-locks the current desired-state row, generation operation, and exact generation + * result through {@link AccountJwtSignerDesiredStateRepository} before touching these rows. The + * repository records intent before external CAS, and its receipts/observations never authorize + * PREPARED, activation, token issuance, or readiness. + */ +@Repository +public class AccountJwtJwksPublicationRepository { + public static final String PUBLIC_JWKS_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_MARKER_DATA_KEY = "jwt-generation.json"; + public static final int MAX_JWKS_BYTES = 256 * 1024; + public static final int MAX_MARKER_BYTES = 16 * 1024; + + private static final String INTENT_TABLE = "account_jwt_jwks_prepublication_intents"; + private static final String RECEIPT_TABLE = "account_jwt_jwks_publication_receipts"; + private static final String MOUNT_TABLE = "account_jwt_jwks_mount_observations"; + private static final String CUSTODY_MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtJwksPublicationRepository( + DSLContext dsl, AccountJwtSignerDesiredStateRepository desiredStateRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + } + + /** + * Returns the current operation's immutable intent, locking its entire owner chain first. A + * missing intent stays missing; reads never create a publication request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentIntent(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + return Optional.of(intent); + } + + /** + * Persists the exact Account-constructed public projection before remote ConfigMap CAS. Only an + * exact same-operation retry can read back the existing row; a changed prior object, public + * bytes, API trust identity, generation result, or active fence is a conflict. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrepublicationIntent recordPrepublicationIntent( + Binding binding, + TrustFence trust, + GenerationResult expectedResult, + GenerationRequest expectedRequest, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedResult, "Exact current generation result is required"); + Objects.requireNonNull(expectedRequest, "Exact current generation request is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult currentResult = readAndLockCurrentResult(binding, trust); + GenerationRequest currentRequest = + desiredStateRepository.readCurrentGenerationRequest(binding, trust); + requireExactGeneration(expectedResult, currentResult, expectedRequest, currentRequest); + PrepublicationIntent candidate = + PrepublicationIntent.create( + currentResult, + currentRequest, + apiBindingDigest, + apiConfigRevision, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + jwksJson, + generationMarkerJson); + + PrepublicationIntent existing = selectIntent(currentResult.operationId(), true); + if (existing != null) { + verifyIntentMatches(currentResult, currentRequest, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS publication intent changed for the same operation"); + } + return existing; + } + + insertIntent(candidate); + PrepublicationIntent readback = selectIntent(currentResult.operationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent did not read back exactly"); + } + return readback; + } + + /** Returns the current operation's persisted intent and optional exact API readback receipt. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPublication(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + PublicationReceipt receipt = selectReceipt(result.operationId(), true); + if (receipt != null) { + verifyReceiptMatches(intent, receipt); + } + MountObservation mount = selectMountObservation(result.operationId(), true); + if (mount != null) { + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWKS observation has no Account publication receipt"); + } + verifyMountMatches(intent, receipt, mount); + } + return Optional.of( + new PublicationEvidence(intent, Optional.ofNullable(receipt), Optional.ofNullable(mount))); + } + + /** + * Recovery-only read of the immutable publication that authorized the exact PREPARED source + * generation. Ordinary current-publication reads remain unavailable while PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public PromotionPublicationEvidence readPreparedPublicationForRecovery( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + GenerationResult result = prepared.generationResult(); + PrepublicationIntent intent = selectIntent(result.operationId(), false); + PublicationReceipt receipt = selectReceipt(result.operationId(), false); + MountObservation mount = selectMountObservation(result.operationId(), false); + if (intent == null || receipt == null || mount == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared generation has no exact public prepublication/readback/mount evidence"); + } + verifyPreparedIntentMatches(prepared, intent); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mount); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared promotion no longer matches its immutable prepublication evidence"); + } + return new PromotionPublicationEvidence(intent, receipt, mount); + } + + /** + * Persists only an exact GET readback from the protected CAS client. No Kubernetes response body, + * bearer token, or private key is stored. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PublicationReceipt recordPublicationReceipt( + Binding binding, + TrustFence trust, + UUID operationId, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String returnedResourceVersion, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(returnedResourceVersion, "observed ConfigMap resourceVersion"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT JWKS receipt is not for the current generation operation"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(operationId, true); + if (intent == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent is missing"); + } + verifyIntentMatches(result, request, intent); + if (!intent.apiBindingDigest().equals(apiBindingDigest) + || !intent.apiConfigRevision().equals(apiConfigRevision) + || !intent.configMapUid().equals(configMapUid) + || !intent.jwksJson().equals(jwksJson) + || !intent.generationMarkerJson().equals(generationMarkerJson)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT JWKS readback does not match the protected publication intent"); + } + + PublicationReceipt candidate = PublicationReceipt.create(intent, returnedResourceVersion); + PublicationReceipt existing = selectReceipt(operationId, true); + if (existing != null) { + verifyReceiptMatches(intent, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS readback changed for the same operation"); + } + return existing; + } + insertReceipt(candidate); + PublicationReceipt readback = selectReceipt(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt did not read back exactly"); + } + return readback; + } + + /** + * Records a local mounted private/public correspondence result only after the exact same + * operation has a persisted API publication receipt. This observation remains non-authorizing. + */ + @Transactional(propagation = Propagation.MANDATORY) + public MountObservation recordMountedCorrespondence( + Binding binding, + TrustFence trust, + UUID operationId, + String generationMarkerDigest, + String mountedPublicDataDigest, + String localPublicKeyFingerprint) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(generationMarkerDigest, "mounted generation marker digest"); + requireDigest(mountedPublicDataDigest, "mounted public projection digest"); + requireDigest(localPublicKeyFingerprint, "mounted public-key fingerprint"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Mounted JWT correspondence is not for the current generation operation"); + } + PrepublicationIntent intent = selectIntent(operationId, true); + PublicationReceipt receipt = selectReceipt(operationId, true); + if (intent == null || receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence has no Account publication receipt"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + verifyIntentMatches(result, request, intent); + verifyReceiptMatches(intent, receipt); + if (!intent.generationMarkerDigest().equals(generationMarkerDigest) + || !intent.publicDataDigest().equals(mountedPublicDataDigest) + || !result.publicKeyFingerprint().equals(localPublicKeyFingerprint)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Mounted JWT correspondence does not match Account's exact publication"); + } + + MountObservation candidate = MountObservation.create(intent, receipt); + MountObservation existing = selectMountObservation(operationId, true); + if (existing != null) { + verifyMountMatches(intent, receipt, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Mounted JWT correspondence changed for the same operation"); + } + return existing; + } + insertMountObservation(candidate, binding); + MountObservation readback = selectMountObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence did not read back exactly"); + } + return readback; + } + + private GenerationResult readAndLockCurrentResult(Binding binding, TrustFence trust) { + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationReceiptDigest().equals(result.receiptDigest()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !request.trustFence().equals(trust)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT publication is not bound to a complete current generation result"); + } + return result; + } + + private static void requireExactGeneration( + GenerationResult expectedResult, + GenerationResult currentResult, + GenerationRequest expectedRequest, + GenerationRequest currentRequest) { + if (!expectedResult.equals(currentResult) || !expectedRequest.equals(currentRequest)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT publication candidate is not the exact current generation result"); + } + } + + private PrepublicationIntent selectIntent(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest FROM " + + INTENT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeIntent(row); + } + + private PublicationReceipt selectReceipt(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest FROM " + + RECEIPT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeReceipt(row); + } + + private MountObservation selectMountObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest FROM " + + MOUNT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeMountObservation(row); + } + + private void insertIntent(PrepublicationIntent intent) { + int inserted = + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-jwks', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.binding().environmentId(), + intent.binding().clusterId(), + intent.binding().namespace(), + CUSTODY_MODE, + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + UUID.fromString(intent.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(intent.trustFence().expectedNamespaceUid()), + intent.trustFence().bindingDigest(), + intent.trustFence().configRevision(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + UUID.fromString(intent.configMapUid()), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + Long.parseLong(intent.targetGeneration()), + intent.targetKid(), + intent.publicKeyFingerprint(), + activeJson(intent.expectedDurableActive()), + activeJson(intent.expectedPublishedActive()), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + intent.intentDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS intent insert was ambiguous"); + } + } + + private void insertReceipt(PublicationReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO " + + RECEIPT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.binding().environmentId(), + receipt.binding().clusterId(), + receipt.binding().namespace(), + receipt.binding().mode().value(), + receipt.intentDigest(), + UUID.fromString(receipt.configMapUid()), + receipt.expectedResourceVersion(), + receipt.observedResourceVersion(), + receipt.publicDataDigest(), + receipt.receiptDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS receipt insert was ambiguous"); + } + } + + private void insertMountObservation(MountObservation observation, Binding binding) { + int inserted = + dsl.execute( + "INSERT INTO " + + MOUNT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + observation.operationId(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + observation.intentDigest(), + observation.publicationReceiptDigest(), + observation.generationMarkerDigest(), + observation.publicDataDigest(), + observation.publicKeyFingerprint(), + observation.observationDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account mounted JWT correspondence insert was ambiguous"); + } + } + + private PrepublicationIntent decodeIntent(Record row) { + try { + Binding binding = + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))); + return new PrepublicationIntent( + row.get("operation_id", UUID.class), + binding, + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired-state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("config_map_name", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("expected_snapshot_digest", String.class), + Long.toString(positive(row.get("target_generation", Long.class), "target generation")), + row.get("target_kid", String.class), + row.get("public_key_fingerprint", String.class), + parseActive(row.get("expected_durable_active_json", String.class)), + parseActive(row.get("expected_published_active_json", String.class)), + row.get("jwks_json", String.class), + row.get("generation_marker_json", String.class), + row.get("public_data_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("intent_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent is malformed", ex); + } + } + + private PublicationReceipt decodeReceipt(Record row) { + try { + return new PublicationReceipt( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))), + row.get("intent_digest", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("observed_resource_version", String.class), + row.get("public_data_digest", String.class), + row.get("receipt_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is malformed", ex); + } + } + + private MountObservation decodeMountObservation(Record row) { + try { + return new MountObservation( + row.get("operation_id", UUID.class), + row.get("intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("public_data_digest", String.class), + row.get("public_key_fingerprint", String.class), + row.get("observation_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account mounted JWT correspondence is malformed", ex); + } + } + + private static void verifyIntentMatches( + GenerationResult result, GenerationRequest request, PrepublicationIntent intent) { + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(request.expectedActive()) + || !intent.expectedPublishedActive().equals(request.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent no longer matches its current generation result"); + } + } + + private static void verifyPreparedIntentMatches( + PreparedGenerationEvidence prepared, PrepublicationIntent intent) { + GenerationResult result = prepared.generationResult(); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(promotion.expectedPreviousActive()) + || !intent.expectedPublishedActive().equals(promotion.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared Account JWKS intent does not match the exact source generation"); + } + } + + private static void verifyReceiptMatches( + PrepublicationIntent intent, PublicationReceipt receipt) { + if (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(intent.binding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !PublicationReceipt.digest(receipt).equals(receipt.receiptDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is not bound to its immutable intent"); + } + } + + private static void verifyMountMatches( + PrepublicationIntent intent, PublicationReceipt receipt, MountObservation observation) { + if (!observation.operationId().equals(intent.operationId()) + || !observation.intentDigest().equals(intent.intentDigest()) + || !observation.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !observation.generationMarkerDigest().equals(intent.generationMarkerDigest()) + || !observation.publicDataDigest().equals(intent.publicDataDigest()) + || !observation.publicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !MountObservation.digest(observation).equals(observation.observationDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence is not bound to its exact Account publication"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT JWKS persistence requires the owning Account transaction"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Account JWT JWKS persistence transaction must be writable"); + } + } + + private static void requireExactCurrentIdentity( + Binding binding, + TrustFence trust, + GenerationResult result, + String apiBindingDigest, + String apiConfigRevision) { + if (!result.binding().equals(binding) + || !result.trustFence().equals(trust) + || !result.trustFence().bindingDigest().equals(trust.bindingDigest()) + || !result.trustFence().configRevision().equals(trust.configRevision())) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT publication trust identity changed"); + } + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS canonicalization is unavailable"); + } + } + + private static AccountJwtSignerDesiredStateRepository.CustodyMode parseCustodyMode(String value) { + for (AccountJwtSignerDesiredStateRepository.CustodyMode candidate : + AccountJwtSignerDesiredStateRepository.CustodyMode.values()) { + if (candidate.value().equals(value)) { + return candidate; + } + } + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "JWT signer custody mode is unsupported"); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireRevision(String value, String field) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireResourceVersion(String value, String field) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireBounded(String value, int limit, String field) { + if (value == null || value.isBlank() || value.getBytes(StandardCharsets.UTF_8).length > limit) { + throw new IllegalArgumentException("JWT signer " + field + " is missing or oversized"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException("JWT signer " + field + " is not positive"); + } + return value; + } + + private static String activeJson(Optional active) { + Map value = new LinkedHashMap<>(); + value.put("present", active.isPresent()); + active.ifPresent( + signer -> { + value.put("generation", signer.generation()); + value.put("kid", signer.kid()); + }); + return new String(canonicalJson(value), StandardCharsets.UTF_8); + } + + private static Optional parseActive(String json) { + try { + tools.jackson.databind.JsonNode node = JSON.readTree(json); + if (node == null || !node.isObject() || !node.has("present")) { + throw new IllegalArgumentException(); + } + if (node.size() == 1 + && node.get("present").isBoolean() + && !node.get("present").booleanValue()) { + return Optional.empty(); + } + if (node.size() == 3 + && node.get("present").isBoolean() + && node.get("present").booleanValue() + && node.get("generation").isTextual() + && node.get("kid").isTextual()) { + return Optional.of( + new ActiveSigner(node.get("generation").textValue(), node.get("kid").textValue())); + } + throw new IllegalArgumentException(); + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer active fence is malformed", ex); + } + } + + /** Fixed non-secret Account intent recorded before an external ConfigMap CAS. */ + public record PrepublicationIntent( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest, + String intentDigest) { + public PrepublicationIntent { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + if (desiredStateVersion <= 1L) { + throw new IllegalArgumentException("JWT signer desired-state version is invalid"); + } + Objects.requireNonNull(trustFence, "JWT signer trust fence is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + if (!PUBLIC_JWKS_NAME.equals(configMapName)) { + throw new IllegalArgumentException("JWT signer public ConfigMap name is not fixed"); + } + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("JWT signer target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("JWT signer target kid is malformed"); + } + requireDigest(publicKeyFingerprint, "public-key fingerprint"); + expectedDurableActive = Objects.requireNonNull(expectedDurableActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + requireDigest(publicDataDigest, "public data digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(intentDigest, "prepublication intent digest"); + if (!publicDataDigest.equals( + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson)) + || !generationMarkerDigest.equals(digestUtf8(generationMarkerJson))) { + throw new IllegalArgumentException("JWT signer public projection digest is invalid"); + } + if (!intentDigest.equals( + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest))) { + throw new IllegalArgumentException("JWT signer prepublication intent digest is invalid"); + } + } + + public static PrepublicationIntent create( + GenerationResult result, + GenerationRequest request, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + return create( + result.operationId(), + result.binding(), + result.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.trustFence(), + apiBindingDigest, + apiConfigRevision, + PUBLIC_JWKS_NAME, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + request.expectedActive(), + request.expectedPublishedActive(), + jwksJson, + generationMarkerJson, + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson), + digestUtf8(generationMarkerJson)); + } + + public static PrepublicationIntent create( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + String intentDigest = + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest); + return new PrepublicationIntent( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest, + intentDigest); + } + + static String digest(PrepublicationIntent value) { + return digest( + value.operationId(), + value.binding(), + value.operationDigest(), + value.generationRequestDigest(), + value.generationReceiptDigest(), + value.desiredStateVersion(), + value.trustFence(), + value.apiBindingDigest(), + value.apiConfigRevision(), + value.configMapName(), + value.configMapUid(), + value.expectedResourceVersion(), + value.expectedSnapshotDigest(), + value.targetGeneration(), + value.targetKid(), + value.publicKeyFingerprint(), + value.expectedDurableActive(), + value.expectedPublishedActive(), + value.jwksJson(), + value.generationMarkerJson(), + value.publicDataDigest(), + value.generationMarkerDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-prepublication-intent/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("operationDigest", operationDigest); + preimage.put("generationRequestDigest", generationRequestDigest); + preimage.put("generationReceiptDigest", generationReceiptDigest); + preimage.put("desiredStateVersion", desiredStateVersion); + preimage.put("expectedClusterIncarnationUid", trustFence.expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", trustFence.expectedNamespaceUid()); + preimage.put("trustBindingDigest", trustFence.bindingDigest()); + preimage.put("trustConfigRevision", trustFence.configRevision()); + preimage.put("apiBindingDigest", apiBindingDigest); + preimage.put("apiConfigRevision", apiConfigRevision); + preimage.put("configMapName", configMapName); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("expectedSnapshotDigest", expectedSnapshotDigest); + preimage.put("targetGeneration", targetGeneration); + preimage.put("targetKid", targetKid); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + preimage.put( + "expectedDurableActive", expectedDurableActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedDurableActiveKid", expectedDurableActive.map(ActiveSigner::kid).orElse("")); + preimage.put( + "expectedPublishedActive", + expectedPublishedActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedPublishedActiveKid", expectedPublishedActive.map(ActiveSigner::kid).orElse("")); + preimage.put("jwksJson", jwksJson); + preimage.put("generationMarkerJson", generationMarkerJson); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Exact ConfigMap readback; it proves publication only, never activation/readiness. */ + public record PublicationReceipt( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public PublicationReceipt { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireResourceVersion(observedResourceVersion, "observed ConfigMap resourceVersion"); + requireDigest(publicDataDigest, "published public data digest"); + requireDigest(receiptDigest, "publication receipt digest"); + if (expectedResourceVersion.equals(observedResourceVersion)) { + throw new IllegalArgumentException("Account JWT ConfigMap resourceVersion did not advance"); + } + if (!receiptDigest.equals( + digest( + operationId, + binding, + intentDigest, + configMapUid, + expectedResourceVersion, + observedResourceVersion, + publicDataDigest))) { + throw new IllegalArgumentException("Account JWT publication receipt digest is invalid"); + } + } + + public static PublicationReceipt create( + PrepublicationIntent intent, String observedResourceVersion) { + String receiptDigest = + digest( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest()); + return new PublicationReceipt( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest(), + receiptDigest); + } + + static String digest(PublicationReceipt value) { + return digest( + value.operationId(), + value.binding(), + value.intentDigest(), + value.configMapUid(), + value.expectedResourceVersion(), + value.observedResourceVersion(), + value.publicDataDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-publication-receipt/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("intentDigest", intentDigest); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("publicDataDigest", publicDataDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Non-secret Account-local observation of the published private/public mounted projection. */ + public record MountObservation( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint, + String observationDigest) { + public MountObservation { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(publicDataDigest, "mounted public data digest"); + requireDigest(publicKeyFingerprint, "mounted public-key fingerprint"); + requireDigest(observationDigest, "mounted observation digest"); + if (!observationDigest.equals( + digest( + operationId, + intentDigest, + publicationReceiptDigest, + generationMarkerDigest, + publicDataDigest, + publicKeyFingerprint))) { + throw new IllegalArgumentException("Mounted JWT observation digest is invalid"); + } + } + + public static MountObservation create(PrepublicationIntent intent, PublicationReceipt receipt) { + String observationDigest = + digest( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint()); + return new MountObservation( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint(), + observationDigest); + } + + static String digest(MountObservation value) { + return digest( + value.operationId(), + value.intentDigest(), + value.publicationReceiptDigest(), + value.generationMarkerDigest(), + value.publicDataDigest(), + value.publicKeyFingerprint()); + } + + private static String digest( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-mounted-correspondence/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("intentDigest", intentDigest); + preimage.put("publicationReceiptDigest", publicationReceiptDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + return sha256(canonicalJson(preimage)); + } + } + + public record PublicationEvidence( + PrepublicationIntent intent, + Optional receipt, + Optional mountedCorrespondence) { + public PublicationEvidence { + Objects.requireNonNull(intent); + receipt = Objects.requireNonNull(receipt); + mountedCorrespondence = Objects.requireNonNull(mountedCorrespondence); + } + } + + public record PromotionPublicationEvidence( + PrepublicationIntent intent, + PublicationReceipt receipt, + MountObservation mountedCorrespondence) { + public PromotionPublicationEvidence { + Objects.requireNonNull(intent); + Objects.requireNonNull(receipt); + Objects.requireNonNull(mountedCorrespondence); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mountedCorrespondence); + } + } + + /** Canonical digest of all observed ConfigMap data used as the pre-CAS compare fence. */ + public static String snapshotDigest(Map data) { + Objects.requireNonNull(data, "ConfigMap data is required"); + if (data.size() > 128) { + throw new IllegalArgumentException("JWT public ConfigMap data has too many entries"); + } + long totalBytes = 0L; + Map bounded = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + if (entry.getKey() == null + || entry.getKey().isBlank() + || entry.getKey().length() > 253 + || entry.getValue() == null) { + throw new IllegalArgumentException("JWT public ConfigMap data is malformed"); + } + totalBytes += entry.getKey().getBytes(StandardCharsets.UTF_8).length; + totalBytes += entry.getValue().getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > 1024L * 1024L) { + throw new IllegalArgumentException("JWT public ConfigMap data is oversized"); + } + bounded.put(entry.getKey(), entry.getValue()); + } + return sha256(canonicalJson(bounded)); + } + + public static String publicDataDigest(String jwksJson, String generationMarkerJson) { + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + Map data = new LinkedHashMap<>(); + data.put(JWKS_DATA_KEY, jwksJson); + data.put(GENERATION_MARKER_DATA_KEY, generationMarkerJson); + return sha256(canonicalJson(data)); + } + + private static String digestUtf8(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java new file mode 100644 index 0000000000..716bbb12e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -0,0 +1,4246 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable, operation-scoped readiness-probe planning and result evidence for Account's interim + * mounted signer. + * + *

This repository never advances signer lifecycle state. It can record only a validator + * observation already authenticated and verified by the owner-internal readiness service. Every + * operation re-locks and compares the existing desired-state, generation, JWKS publication, and + * mounted-correspondence authorities; probe plans are evidence attached to that owner operation, + * not a second key authority. + */ +@Repository +public class AccountJwtReadinessProbeRepository { + public static final int MAX_VALIDATOR_CACHE_AGE_SECONDS = 300; + public static final int PROBE_LIFETIME_SECONDS = 300; + public static final int MAX_ENTRIES_PER_OPERATION = 256; + public static final int MAX_POD_RECEIPTS_PER_OPERATION = 256; + public static final String INVENTORY_STATUS = "PARTIAL_UNCONFIRMED"; + public static final int INVENTORY_PLAN_VERSION = 2; + + private static final String PLAN_TABLE = "account_jwt_readiness_probe_plans"; + private static final String ENTRY_TABLE = "account_jwt_readiness_probe_entries"; + private static final String DELIVERY_CLAIM_TABLE = "account_jwt_readiness_delivery_claims"; + private static final String EXPECTED_POD_TABLE = "account_jwt_readiness_validator_pods"; + private static final String POD_RECEIPT_TABLE = "account_jwt_readiness_pod_receipts"; + private static final String VALIDATOR_ID = "account-service"; + private static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + private static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + private static final String CONTROL_UI_PROFILE = ControlUiJwtProfileValidator.PROFILE; + private static final String CONTROL_UI_AUDIENCE = ControlUiJwtProfileValidator.AUDIENCE; + private static final String PLAYER_BOOTSTRAP_PROFILE = PlayerBootstrapJwtProfileValidator.PROFILE; + private static final String PLAYER_BOOTSTRAP_AUDIENCE = + PlayerBootstrapJwtProfileValidator.AUDIENCE; + private static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String REPRESENTATIVE_AUDIENCE = + GameSessionAccountDelegationProfile.AUDIENCE; + private static final List PRODUCTION_PROFILE_CASES = + List.of( + new ProfileCase(CONTROL_UI_PROFILE, CONTROL_UI_AUDIENCE), + new ProfileCase(PLAYER_BOOTSTRAP_PROFILE, PLAYER_BOOTSTRAP_AUDIENCE), + new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE)); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtValidatorInventoryRepository inventoryRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators and constructs an in-memory repository; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository) { + this( + dsl, + desiredStateRepository, + publicationRepository, + new AccountJwtValidatorInventoryRepository(dsl)); + } + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtValidatorInventoryRepository inventoryRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.inventoryRepository = + Objects.requireNonNull(inventoryRepository, "Inventory repository is required"); + } + + /** + * Creates one immutable plan from the exact current Account operation and publication evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust, Instant plannedAt) { + return planCurrent(binding, trust, plannedAt, Optional.empty()); + } + + /** + * Reads the exact current operation context before protected inventory I/O. The caller must + * return to an Account transaction and recheck this context before persisting or consuming the + * resulting snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + ReadinessProbePlan existing = selectPlan(current.request().operationId(), false); + if (existing != null) { + requirePlanMatchesCurrent(readbackPlan(existing, false), current); + } + return observationContext(current); + } + + /** Reads the selected context only while its exact current V2 inventory plan remains current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + throw new ReceiverUnavailableException(); + } + return observationContext(current); + } + + /** + * Creates a still-partial plan bound to the exact Account-owned immutable inventory snapshot. The + * live inventory observation does not establish per-Pod acceptance or promotion evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent( + Binding binding, TrustFence trust, Instant plannedAt, InventorySnapshot inventorySnapshot) { + return planCurrent( + binding, trust, plannedAt, Optional.of(Objects.requireNonNull(inventorySnapshot))); + } + + private ReadinessProbePlan planCurrent( + Binding binding, + TrustFence trust, + Instant plannedAt, + Optional inventorySnapshot) { + requireWritableAccountTransaction(); + Objects.requireNonNull(plannedAt, "Probe plan time is required"); + long plannedEpoch = exactEpochSecond(plannedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + UUID operationId = current.request().operationId(); + ReadinessProbePlan existing = selectPlan(operationId, true); + if (existing != null) { + requirePlanMatchesCurrent(existing, current); + if (inventorySnapshot.isPresent()) { + String requestedDigest = inventorySnapshot.orElseThrow().digest(); + if (!existing.inventorySnapshotDigest().equals(Optional.of(requestedDigest))) { + throw new InventoryPlanConflictException(); + } + inventoryRepository.readRequired(requestedDigest, binding, trust); + } + return readbackPlan(existing, true); + } + + Optional snapshotDigest = Optional.empty(); + if (inventorySnapshot.isPresent()) { + InventorySnapshot snapshot = inventorySnapshot.orElseThrow(); + requireObservationContext(current, snapshot); + requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.persistOrReadback(snapshot, binding, trust); + snapshotDigest = Optional.of(stored.digest()); + } + ReadinessProbePlan candidate = + newPlan(current, plannedEpoch, inventorySnapshot, snapshotDigest); + insertPlan(candidate); + for (ProbeEntry entry : candidate.entries()) { + insertEntry(entry, candidate.planVersion()); + } + if (inventorySnapshot.isPresent()) { + for (ExpectedPod expectedPod : expectedPods(candidate, inventorySnapshot.orElseThrow())) { + insertExpectedPod(expectedPod); + } + } + ReadinessProbePlan readback = selectPlan(operationId, true); + if (readback == null) { + throw new StorageUnavailableException("Account JWT readiness probe plan did not read back"); + } + requirePlanMatchesCurrent(readback, current); + if (!candidate.equals(readback)) { + throw new QuarantinedStateException("Account JWT readiness probe plan changed on readback"); + } + return readback; + } + + private static void requireInventorySnapshotWithinPlanWindow( + InventorySnapshot snapshot, long plannedEpoch) { + long observedEpoch; + try { + observedEpoch = snapshot.observedAt().getEpochSecond(); + } catch (RuntimeException failure) { + throw new InventoryPlanConflictException(); + } + if (observedEpoch <= 0L + || observedEpoch > plannedEpoch + || plannedEpoch - observedEpoch > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new InventoryPlanConflictException(); + } + } + + /** + * Durably claims the one transient delivery attempt for this exact current plan before signing. A + * claim is never cleared or reused: a lost response or interrupted attempt remains quarantined. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim claimSingleDelivery( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + Instant claimedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(readinessBinding, "Authenticated readiness binding is required"); + Objects.requireNonNull(peer, "TLS-authenticated readiness peer is required"); + long claimedEpoch = exactEpochSecond(claimedAt); + if (!readinessBinding.isCurrentAt(claimedEpoch) + || !readinessBinding.matches(peer) + || !binding.environmentId().equals(readinessBinding.environmentId()) + || !binding.clusterId().equals(readinessBinding.clusterId()) + || !binding.namespace().equals(readinessBinding.namespace()) + || !trust + .expectedClusterIncarnationUid() + .equals(readinessBinding.expectedClusterIncarnationUid()) + || !trust.expectedNamespaceUid().equals(readinessBinding.expectedNamespaceUid())) { + throw new DeliveryClaimRejectedException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan stored = requireStoredPlan(current); + ReadinessProbePlan currentPlan = readbackPlan(stored, true); + if (!currentPlan.equals(expectedPlan)) { + throw new StaleOperationException( + "Readiness delivery claim does not match the exact current plan"); + } + if (claimedEpoch < currentPlan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (claimedEpoch >= currentPlan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + if (currentPlan.entries().isEmpty() + || currentPlan.entries().size() > MAX_ENTRIES_PER_OPERATION + || currentPlan.entries().stream() + .anyMatch( + entry -> + entry.state() != ProbeState.PLANNED + || entry.signingAttemptedAtEpochSecond().isPresent() + || entry.compactTokenSha256().isPresent() + || entry.verificationReceipt().isPresent())) { + throw new DeliveryAlreadyClaimedException(); + } + if (selectDeliveryClaim(currentPlan.operationId(), true) != null) { + throw new DeliveryAlreadyClaimedException(); + } + + DeliveryClaim candidate = + DeliveryClaim.create(currentPlan, trust, readinessBinding, peer, claimedEpoch); + insertDeliveryClaim(candidate); + DeliveryClaim readback = selectDeliveryClaim(candidate.rotationOperationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account readiness single-delivery claim did not read back exactly"); + } + return readback; + } + + /** Rechecks the immutable one-shot claim immediately before any pending-key signing. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim requireCurrentDeliveryClaim( + Binding binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + DeliveryClaim expectedClaim, + Instant checkedAt) { + requireAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(expectedClaim, "Durable single-delivery claim is required"); + long checkedEpoch = exactEpochSecond(checkedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan plan = readbackPlan(requireStoredPlan(current), true); + DeliveryClaim persisted = selectDeliveryClaim(plan.operationId(), true); + if (!plan.equals(expectedPlan) + || persisted == null + || !persisted.equals(expectedClaim) + || !persisted.planDigest().equals(plan.planDigest()) + || !persisted.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !persisted.materializerTrustConfigRevision().equals(trust.configRevision()) + || !persisted.expectedClusterUid().equals(trust.expectedClusterIncarnationUid()) + || !persisted.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !persisted.targetGeneration().equals(plan.targetGeneration()) + || !persisted.targetKid().equals(plan.targetKid())) { + throw new DeliveryAlreadyClaimedException(); + } + if (checkedEpoch < plan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (checkedEpoch >= plan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + return persisted; + } + + /** + * Reads the exact current generation and public publication before PREPARED so the caller can + * authorize that same generation's preparation. The static applicability matrix and immutable + * Deployment inventory snapshot alone are not per-Pod acceptance evidence; partial plans cannot + * satisfy promotion. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readCurrentPromotionPrerequisites(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // This is a nonmutating proof read, but it joins the writable lifecycle transaction because + // the existing owner evidence readers lock their rows to fence the adjacent PREPARED CAS. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(rotationOperationId)) { + throw new StaleOperationException( + "Readiness prerequisite proof is not for Account's current operation"); + } + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Current signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePlanMatchesCurrent(stored, current); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches(stored, binding, trust, liveInventory, observationContext(current)); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + promotionPublicationEvidence(current.publication()); + return Optional.of( + new ReadinessPromotionProof( + stored, + current.result(), + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readPromotionProof(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // Recovery evidence is likewise a locked, nonmutating read inside the writable reconciliation + // transaction; do not split these reads into an unlocked read-only snapshot. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + var prepared = desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + var generation = prepared.generationResult(); + var promotion = prepared.promotion(); + if (!generation.operationId().equals(rotationOperationId) + || !promotion.generationOperationId().equals(rotationOperationId) + || !promotion.binding().equals(binding) + || !promotion.trustFence().equals(trust)) { + throw new StaleOperationException( + "Readiness promotion proof does not match the exact PREPARED generation"); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + publicationRepository.readPreparedPublicationForRecovery(binding, trust); + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Prepared signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePreparedPlanMatches(stored, generation, promotion, publication); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches( + stored, + binding, + trust, + liveInventory, + observationContext( + generation.operationId(), generation.operationDigest(), stored.expectedFence())); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + return Optional.of( + new ReadinessPromotionProof( + stored, + generation, + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); + } + + private boolean readinessPlanOutOfWindow(ReadinessProbePlan plan) { + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness database clock readback is unavailable"); + } + return databaseNow < plan.notBeforeEpochSecond() || databaseNow >= plan.expiresAtEpochSecond(); + } + + /** Reads one plan only while its original generation and publication evidence remain current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(operationId)) { + throw new StaleOperationException( + "Readiness probe plan is not for Account's current operation"); + } + ReadinessProbePlan stored = selectPlan(operationId, true); + if (stored == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(stored, current); + return readbackPlan(stored, true); + } + + /** Reads one exact current probe selected by the complete key and its immutable JTI. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry readCurrentEntry( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest())) { + throw new StaleOperationException("Readiness probe selector is not the exact current entry"); + } + return entry; + } + + /** + * Records only the exact authenticated, cryptographically verified observation for one current + * ISSUED entry. A matching VERIFIED retry reads back the original immutable receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordVerified( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + VerifiedProbeObservation observation) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + Objects.requireNonNull(observation, "Authenticated verification observation is required"); + long observedAt = exactEpochSecond(Instant.ofEpochSecond(observation.observedAtEpochSecond())); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.targetGeneration().equals(plan.targetGeneration()) + || !entry.targetKid().equals(plan.targetKid()) + || !entry.expectedActive().equals(plan.expectedFence().durableActive()) + || !entry.expectedActive().equals(plan.expectedFence().publishedActive()) + || entry.registryVersion() != 1 + || !entry.compactTokenSha256().equals(Optional.of(observation.compactTokenSha256())) + || !entry.targetKid().equals(observation.verifiedKid())) { + throw new StaleOperationException( + "Verified readiness probe does not match the exact current operation entry"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + if (entry.state() == ProbeState.VERIFIED) { + VerificationReceipt existing = + entry + .verificationReceipt() + .orElseThrow( + () -> + new QuarantinedStateException( + "Verified readiness entry has no immutable receipt")); + requireMatchingObservation(existing, observation); + return entry; + } + if (entry.state() != ProbeState.ISSUED || entry.verificationReceipt().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe is not the exact current ISSUED entry"); + } + + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt receipt = verificationReceipt(plan, entry, observation, resultEntryVersion); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND state = 'ISSUED' AND entry_version = ? AND target_generation = ? " + + "AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + receipt.resultEntryVersion(), + receipt.receiptVersion(), + receipt.sourceEntryVersion(), + receipt.observedAtEpochSecond(), + receipt.verifiedKid(), + receipt.validatorInstanceId(), + receipt.validatorBindingDigest(), + receipt.validatorConfigRevision(), + receipt.validatorPeerUri(), + receipt.validatorPeerSpkiSha256(), + receipt.receiptSha256(), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name(), + jti, + plan.planDigest(), + entry.entryVersion(), + Long.parseLong(plan.targetGeneration()), + plan.targetKid(), + observation.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness VERIFIED transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != receipt.resultEntryVersion() + || readback.verificationReceipt().filter(receipt::equals).isEmpty()) { + throw new QuarantinedStateException("Verified readiness receipt did not read back exactly"); + } + return readback; + } + + /** + * Pins the exact signed-token hash before delivery. A row with this pin but no ISSUED result is + * ambiguous after a crash and must be quarantined; it is never signed or delivered again. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordSigningAttempt( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant attemptedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long attemptedEpoch = exactEpochSecond(attemptedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, attemptedEpoch); + if (attemptedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isPresent() + || entry.signingAttemptedAtEpochSecond().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe already has a signing attempt"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET signing_attempted_at_epoch_seconds = ?, compact_token_sha256 = ?, " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ? " + + "AND validator_id = ? AND token_profile = ? AND audience = ? AND probe_kind = ? " + + "AND plan_digest = ? AND state = 'PLANNED' AND entry_version = ? " + + "AND compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL", + attemptedEpoch, + signed.compactTokenSha256(), + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe signing attempt lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.PLANNED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || !readback.signingAttemptedAtEpochSecond().equals(Optional.of(attemptedEpoch))) { + throw new QuarantinedStateException( + "Readiness probe signing attempt did not read back exactly"); + } + return readback; + } + + /** Durably records ISSUED before the exact compact probe reaches its transient consumer. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordIssued( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant issuedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long issuedEpoch = exactEpochSecond(issuedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, issuedEpoch); + if (issuedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() == ProbeState.ISSUED) { + if (!entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new IdempotencyConflictException("Issued readiness probe hash changed"); + } + return entry; + } + if (entry.state() != ProbeState.PLANNED + || !entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || entry.signingAttemptedAtEpochSecond().isEmpty()) { + throw new AmbiguousDeliveryException("Readiness probe is not pinned for exact delivery"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'ISSUED', entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND plan_digest = ? " + + "AND state = 'PLANNED' AND entry_version = ? AND compact_token_sha256 = ? " + + "AND signing_attempted_at_epoch_seconds IS NOT NULL", + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion(), + signed.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe ISSUED transition lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.ISSUED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new QuarantinedStateException("Issued readiness probe did not read back exactly"); + } + return readback; + } + + /** Quarantines a pinned PLANNED attempt after delivery or persistence became ambiguous. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry abortAmbiguousAttempt( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isEmpty()) { + throw new AmbiguousDeliveryException("No ambiguous pinned readiness attempt exists"); + } + return transitionTerminal(entry, ProbeState.ABORTED, terminalEpoch); + } + + /** Aborts only entries belonging to the exact current Account operation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List abortCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if (currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) { + result.add(transitionTerminal(currentEntry, ProbeState.ABORTED, terminalEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** Expires only this exact current operation after its immutable entry expiry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List expireCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant now) { + requireWritableAccountTransaction(); + long nowEpoch = exactEpochSecond(now); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if ((currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) + && nowEpoch >= currentEntry.expiresAtEpochSecond()) { + result.add(transitionTerminal(currentEntry, ProbeState.EXPIRED, nowEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** + * Bounded cleanup of terminal entries for one explicit operation. It never queries or scans + * another operation and retains all non-secret identity/hash/terminal evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List cleanTerminalEntries(UUID operationId, int maximumEntries) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + if (maximumEntries < 1 || maximumEntries > MAX_ENTRIES_PER_OPERATION) { + throw new IllegalArgumentException("Readiness cleanup bound is outside its fixed limit"); + } + Result terminalRows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND state IN ('ABORTED', 'EXPIRED') " + + "ORDER BY validator_id, token_profile, audience, probe_kind LIMIT ? FOR UPDATE", + operationId, + maximumEntries); + if (terminalRows.size() > maximumEntries) { + throw new QuarantinedStateException("Readiness cleanup exceeded its exact operation bound"); + } + List cleaned = new ArrayList<>(); + for (Record row : terminalRows) { + ProbeEntry entry = decodeEntry(row); + cleaned.add(transitionTerminal(entry, ProbeState.CLEANED, null)); + } + return List.copyOf(cleaned); + } + + private ProbeEntry transitionTerminal(ProbeEntry entry, ProbeState target, Long transitionEpoch) { + if (target == ProbeState.EXPIRED && transitionEpoch == null) { + throw new IllegalArgumentException("Expiry time is required"); + } + String outcome = + target == ProbeState.CLEANED ? entry.terminalOutcome().orElseThrow() : target.name(); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = ?, terminal_outcome = ?, entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND state = ? AND entry_version = ?", + target.name(), + outcome, + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.state().name(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness terminal transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != target + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.terminalOutcome().equals(Optional.of(outcome))) { + throw new QuarantinedStateException( + "Readiness terminal transition did not read back exactly"); + } + return readback; + } + + private ReadinessProbePlan newPlan( + CurrentEvidence current, + long plannedAtEpochSecond, + Optional inventorySnapshot, + Optional inventorySnapshotDigest) { + long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); + long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); + int planVersion = inventorySnapshot.isPresent() ? INVENTORY_PLAN_VERSION : 1; + boolean inventoryComplete = + inventorySnapshot + .map(AccountJwtReadinessProbeRepository::inventoryPlanComplete) + .orElse(false); + String matrixJson = + inventorySnapshot + .map(snapshot -> applicabilityMatrixJson(snapshot, inventoryComplete)) + .orElseGet(AccountJwtReadinessProbeRepository::applicabilityMatrixJson); + String matrixDigest = sha256(matrixJson.getBytes(StandardCharsets.UTF_8)); + List entries = + (inventorySnapshot.isPresent() + ? inventoryEntries(current, inventorySnapshot.orElseThrow(), notBefore, expiresAt) + : legacyEntries(current, notBefore, expiresAt)) + .stream().sorted(PROBE_ENTRY_ORDER).toList(); + String planDigest = + planDigest( + current, + matrixJson, + matrixDigest, + planVersion, + inventoryComplete, + plannedAtEpochSecond, + notBefore, + expiresAt, + entries, + inventorySnapshotDigest); + List boundEntries = + entries.stream().map(entry -> entry.withPlanDigest(planDigest)).toList(); + return ReadinessProbePlan.fromCurrent( + current, + matrixJson, + matrixDigest, + inventoryComplete, + MAX_VALIDATOR_CACHE_AGE_SECONDS, + plannedAtEpochSecond, + notBefore, + expiresAt, + planDigest, + boundEntries, + inventorySnapshotDigest, + planVersion); + } + + private static List legacyEntries( + CurrentEvidence current, long notBefore, long expiresAt) { + return List.of( + newEntry( + current, + VALIDATOR_ID, + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + CONTROL_UI_PROFILE, + CONTROL_UI_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + PLAYER_BOOTSTRAP_PROFILE, + PLAYER_BOOTSTRAP_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + REPRESENTATIVE_PROFILE, + REPRESENTATIVE_AUDIENCE, + notBefore, + expiresAt)); + } + + private static List inventoryEntries( + CurrentEvidence current, InventorySnapshot snapshot, long notBefore, long expiresAt) { + List entries = new ArrayList<>(); + for (ValidatorObservation validator : snapshot.validators()) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt)); + for (ProfileCase profile : PRODUCTION_PROFILE_CASES) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.REPRESENTATIVE, + profile.tokenProfile(), + profile.audience(), + notBefore, + expiresAt)); + } + } + if (entries.isEmpty() || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(entries); + } + + private static ProbeEntry newEntry( + CurrentEvidence current, + String validatorId, + ProbeKind kind, + String profile, + String audience, + long notBefore, + long expiresAt) { + return new ProbeEntry( + current.request().operationId(), + "0".repeat(64), + validatorId, + profile, + audience, + kind, + UUID.randomUUID(), + current.request().targetGeneration(), + current.request().targetKid(), + current.state().durableActive(), + 1, + 1, + notBefore, + expiresAt, + ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private void insertPlan(ReadinessProbePlan plan) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", plan.operationId()); + fields.put("environment_id", plan.binding().environmentId()); + fields.put("cluster_id", plan.binding().clusterId()); + fields.put("kubernetes_namespace", plan.binding().namespace()); + fields.put("custody_mode", plan.binding().mode().value()); + fields.put("operation_digest", plan.operationDigest()); + fields.put("generation_request_digest", plan.generationRequestDigest()); + fields.put("generation_receipt_digest", plan.generationReceiptDigest()); + fields.put("desired_state_version", plan.desiredStateVersion()); + fields.put( + "expected_cluster_incarnation_uid", + UUID.fromString(plan.trustFence().expectedClusterIncarnationUid())); + fields.put("expected_namespace_uid", UUID.fromString(plan.trustFence().expectedNamespaceUid())); + fields.put("trust_binding_digest", plan.trustFence().bindingDigest()); + fields.put("trust_config_revision", plan.trustFence().configRevision()); + fields.put("target_generation", Long.parseLong(plan.targetGeneration())); + fields.put("target_kid", plan.targetKid()); + fields.put("target_public_key_fingerprint", plan.targetPublicKeyFingerprint()); + fields.put( + "expected_active_generation", + plan.expectedFence() + .durableActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_active_kid", + plan.expectedFence().durableActive().map(ActiveSigner::kid).orElse(null)); + fields.put( + "expected_published_generation", + plan.expectedFence() + .publishedActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_published_kid", + plan.expectedFence().publishedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("publication_intent_digest", plan.publicationIntentDigest()); + fields.put("publication_receipt_digest", plan.publicationReceiptDigest()); + fields.put("mounted_observation_digest", plan.mountedObservationDigest()); + fields.put("applicability_matrix_json", plan.applicabilityMatrixJson()); + fields.put("applicability_matrix_digest", plan.applicabilityMatrixDigest()); + fields.put("validator_inventory_complete", plan.validatorInventoryComplete()); + fields.put("inventory_snapshot_digest", plan.inventorySnapshotDigest().orElse(null)); + fields.put("maximum_cache_age_seconds", plan.maximumCacheAgeSeconds()); + fields.put("planned_at_epoch_seconds", plan.plannedAtEpochSecond()); + fields.put("not_before_epoch_seconds", plan.notBeforeEpochSecond()); + fields.put("expires_at_epoch_seconds", plan.expiresAtEpochSecond()); + fields.put("plan_version", plan.planVersion()); + fields.put("plan_digest", plan.planDigest()); + insertOne(dsl, PLAN_TABLE, fields); + } + + private void insertDeliveryClaim(DeliveryClaim claim) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", claim.rotationOperationId()); + fields.put("plan_digest", claim.planDigest()); + fields.put("expected_cluster_incarnation_uid", UUID.fromString(claim.expectedClusterUid())); + fields.put("expected_namespace_uid", UUID.fromString(claim.expectedNamespaceUid())); + fields.put("materializer_trust_binding_digest", claim.materializerTrustBindingDigest()); + fields.put("materializer_trust_config_revision", claim.materializerTrustConfigRevision()); + fields.put("target_generation", Long.parseLong(claim.targetGeneration())); + fields.put("target_kid", claim.targetKid()); + fields.put( + "expected_active_generation", + claim.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", claim.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("readiness_binding_digest", claim.readinessBindingDigest()); + fields.put("readiness_config_revision", claim.readinessConfigRevision()); + fields.put( + "readiness_binding_valid_until_epoch_seconds", + claim.readinessBindingValidUntilEpochSecond()); + fields.put("validator_id", claim.validatorId()); + fields.put("validator_instance_id", claim.validatorInstanceId()); + fields.put("validator_peer_uri", claim.validatorPeerUri()); + fields.put("validator_peer_spki_sha256", claim.validatorPeerSpkiSha256()); + fields.put("claimed_at_epoch_seconds", claim.claimedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", claim.expiresAtEpochSecond()); + fields.put("claim_digest", claim.claimDigest()); + insertOne(dsl, DELIVERY_CLAIM_TABLE, fields); + } + + private DeliveryClaim selectDeliveryClaim(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + DELIVERY_CLAIM_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + return null; + } + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + DeliveryClaim result = + new DeliveryClaim( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + row.get("readiness_binding_digest", String.class), + row.get("readiness_config_revision", String.class), + row.get("readiness_binding_valid_until_epoch_seconds", Long.class), + row.get("validator_id", String.class), + row.get("validator_instance_id", String.class), + row.get("validator_peer_uri", String.class), + row.get("validator_peer_spki_sha256", String.class), + row.get("claimed_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("claim_digest", String.class)); + if (!result.claimDigest().equals(deliveryClaimDigest(result))) { + throw new QuarantinedStateException("Account readiness delivery claim digest is invalid"); + } + return result; + } + + private void insertEntry(ProbeEntry entry, int planVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", entry.rotationOperationId()); + fields.put("plan_digest", entry.planDigest()); + fields.put("validator_id", entry.validatorId()); + fields.put("token_profile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probe_kind", entry.probeKind().name()); + fields.put("jti", entry.jti()); + fields.put("target_generation", Long.parseLong(entry.targetGeneration())); + fields.put("target_kid", entry.targetKid()); + fields.put( + "expected_active_generation", + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", entry.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("registry_version", entry.registryVersion()); + fields.put("entry_version", entry.entryVersion()); + fields.put("planned_issued_at_epoch_seconds", entry.plannedIssuedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", entry.expiresAtEpochSecond()); + fields.put("state", entry.state().name()); + fields.put("entry_plan_version", planVersion); + fields.put("terminal_outcome", null); + fields.put("signing_attempted_at_epoch_seconds", null); + fields.put("compact_token_sha256", null); + insertOne(dsl, ENTRY_TABLE, fields); + } + + private void insertExpectedPod(ExpectedPod expected) { + PodTarget target = expected.target(); + target.requireRoutablePodIdentity(); + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", expected.rotationOperationId()); + fields.put("plan_digest", expected.planDigest()); + fields.put("validator_id", expected.validatorId()); + fields.put("token_profile", expected.tokenProfile()); + fields.put("audience", expected.audience()); + fields.put("probe_kind", expected.probeKind().name()); + fields.put("jti", expected.jti()); + fields.put("inventory_snapshot_digest", target.inventorySnapshotDigest()); + fields.put("environment_id", target.environmentId()); + fields.put("cluster_id", target.clusterId()); + fields.put("cluster_incarnation_uid", UUID.fromString(target.clusterIncarnationUid())); + fields.put("kubernetes_namespace", target.namespace()); + fields.put("namespace_uid", UUID.fromString(target.namespaceUid())); + fields.put("api_binding_revision", target.apiBindingRevision()); + fields.put("api_binding_digest", target.apiBindingDigest()); + fields.put("inventory_binding_revision", target.inventoryBindingRevision()); + fields.put("inventory_binding_digest", target.inventoryBindingDigest()); + fields.put("deployment_uid", UUID.fromString(target.deploymentUid())); + fields.put("pod_uid", UUID.fromString(target.podUid())); + fields.put("pod_ip", target.podIp()); + fields.put("image", target.image()); + fields.put("verifier_config_sha256", target.verifierConfigSha256()); + fields.put("applicability_matrix_digest", target.applicabilityMatrixDigest()); + fields.put("expected_outcome", target.expectation().name()); + fields.put("exact_pod_endpoint", target.exactPodEndpoint().map(URI::toString).orElse(null)); + fields.put("canonical_service_uri", target.canonicalServiceUri().orElse(null)); + fields.put("expected_pod_leaf_spki_sha256", target.podLeafSpkiSha256().orElse(null)); + insertOne(dsl, EXPECTED_POD_TABLE, fields); + } + + /** Reads the immutable, exact per-Pod plan rows for one current V2 entry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry expectedEntry) { + throw new ReceiverUnavailableException(); + } + + /** Reads exact expected Pod rows only after a fresh independent owner observation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + InventorySnapshot liveInventory) { + requireAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry stored = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (stored == null + || !stored.equals(expectedEntry) + || stored.state() != ProbeState.ISSUED + || stored.compactTokenSha256().isEmpty()) { + throw new StaleOperationException("Readiness receiver entry changed before invocation"); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> inventoryRepository.readRequired(digest, binding, trust)); + List expectedPods = selectExpectedPods(stored, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness V2 entry has no bounded expected Pod set"); + } + return expectedPods; + } + + /** + * Reads only the owner-retained coordinates and one Pod target for the authenticated V2 receiver + * lookup. The caller's tuple is a selector: every returned coordinate is projected from locked + * current owner rows, never copied from the request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + InventorySnapshot liveInventory, + String authenticatedWorkloadNamespace) { + requireAccountTransaction(); + Objects.requireNonNull(selector, "Exact readiness probe selector is required"); + if (authenticatedWorkloadNamespace == null || authenticatedWorkloadNamespace.isBlank()) { + throw new ReceiverUnavailableException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(selector.rotationOperationId())) { + throw new ReceiverUnavailableException(); + } + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.operationId().equals(selector.rotationOperationId()) + || !plan.operationDigest().equals(selector.operationDigest()) + || !plan.planDigest().equals(selector.planDigest()) + || plan.planVersion() != selector.planVersion() + || plan.expiresAtEpochSecond() != selector.planExpiresAtEpochSecond() + || !plan.targetGeneration().equals(selector.targetGeneration()) + || !plan.targetKid().equals(selector.targetKid()) + || !plan.expectedFence().durableActive().equals(selector.expectedActive()) + || !plan.expectedFence().publishedActive().equals(selector.expectedActive())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + if (readinessPlanOutOfWindow(plan)) { + throw new ReceiverUnavailableException(); + } + + ProbeEntry entry = + selectEntry( + selector.rotationOperationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + true); + if (entry == null + || entry.state() != ProbeState.ISSUED + || entry.verificationReceipt().isPresent() + || !entry.rotationOperationId().equals(selector.rotationOperationId()) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.jti().equals(selector.jti()) + || entry.registryVersion() != selector.registryVersion() + || entry.entryVersion() != selector.entryVersion() + || !entry.targetGeneration().equals(selector.targetGeneration()) + || !entry.targetKid().equals(selector.targetKid()) + || !entry.expectedActive().equals(selector.expectedActive()) + || entry.plannedIssuedAtEpochSecond() != selector.issuedAtEpochSecond() + || entry.expiresAtEpochSecond() != selector.expiresAtEpochSecond() + || !entry.compactTokenSha256().equals(Optional.of(selector.compactTokenSha256()))) { + throw new ReceiverUnavailableException(); + } + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null + || databaseNow < entry.plannedIssuedAtEpochSecond() + || databaseNow >= entry.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + List expectedPods = selectExpectedPods(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new ReceiverUnavailableException(); + } + List selectedPods = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(selector.localIdentity().podUid())) + .toList(); + if (selectedPods.size() != 1) { + throw new ReceiverUnavailableException(); + } + ExpectedPod expectedPod = selectedPods.getFirst(); + PodTarget target = expectedPod.target(); + target.requireRoutablePodIdentity(); + AccountJwtReadinessProbeOwnerSelector.LocalIdentity local = selector.localIdentity(); + if (!target.validatorId().equals(selector.validatorId()) + || !expectedPod.rotationOperationId().equals(selector.rotationOperationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.jti().equals(entry.jti()) + || target.expectation() != selector.expectedOutcome() + || !target.namespace().equals(authenticatedWorkloadNamespace) + || !local.validatorId().equals(target.validatorId()) + || !local.deploymentUid().equals(target.deploymentUid()) + || !local.podUid().equals(target.podUid()) + || !local.podIp().equals(target.podIp()) + || !local.directPodEndpoint().equals(target.exactPodEndpoint().orElseThrow().toString()) + || !local.canonicalServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !local.image().equals(target.image()) + || !local.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !local.applicabilityMatrixDigest().equals(plan.applicabilityMatrixDigest()) + || !local.serverLeafSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow())) { + throw new ReceiverUnavailableException(); + } + return new OwnerProbeEvidence(plan, entry, expectedPod); + } + + /** + * Records one owner-authenticated production verifier result for one exact expected Pod. A + * logical entry remains ISSUED until every immutable expected Pod has a matching unique receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance, + InventorySnapshot liveInventory) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + Objects.requireNonNull(expectedPod, "Exact expected Pod row is required"); + Objects.requireNonNull(acceptance, "Owner-authenticated receiver result is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest()) + || !expectedPod.rotationOperationId().equals(plan.operationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.validatorId().equals(expectedEntry.validatorId()) + || !expectedPod.tokenProfile().equals(expectedEntry.tokenProfile()) + || !expectedPod.audience().equals(expectedEntry.audience()) + || expectedPod.probeKind() != expectedEntry.probeKind() + || !expectedPod.jti().equals(expectedEntry.jti())) { + throw new StaleOperationException("Readiness Pod receipt is outside the exact current entry"); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry entry = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (entry == null + || entry.compactTokenSha256().isEmpty() + || !entry.rotationOperationId().equals(expectedEntry.rotationOperationId()) + || !entry.planDigest().equals(expectedEntry.planDigest()) + || !entry.validatorId().equals(expectedEntry.validatorId()) + || !entry.tokenProfile().equals(expectedEntry.tokenProfile()) + || !entry.audience().equals(expectedEntry.audience()) + || entry.probeKind() != expectedEntry.probeKind() + || !entry.jti().equals(expectedEntry.jti()) + || !entry.targetGeneration().equals(expectedEntry.targetGeneration()) + || !entry.targetKid().equals(expectedEntry.targetKid()) + || !entry.expectedActive().equals(expectedEntry.expectedActive()) + || entry.registryVersion() != expectedEntry.registryVersion() + || entry.plannedIssuedAtEpochSecond() != expectedEntry.plannedIssuedAtEpochSecond() + || entry.expiresAtEpochSecond() != expectedEntry.expiresAtEpochSecond()) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + boolean alreadyVerified = entry.state() == ProbeState.VERIFIED; + if ((!alreadyVerified && entry.state() != ProbeState.ISSUED) + || (!alreadyVerified && !entry.equals(expectedEntry)) + || (alreadyVerified + && (entry.entryVersion() <= 1L + || entry + .verificationReceipt() + .filter(value -> value.receiptVersion() == 2) + .isEmpty()))) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + List expectedPods = selectExpectedPods(entry, true); + ExpectedPod persistedPod = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(expectedPod.target().podUid())) + .findFirst() + .orElseThrow(ReceiverUnavailableException::new); + if (!persistedPod.equals(expectedPod)) { + throw new QuarantinedStateException("Readiness Pod target changed after its immutable plan"); + } + PodTarget target = persistedPod.target(); + target.requireRoutablePodIdentity(); + long observedAt = acceptance.observedAtEpochSecond(); + if (!acceptance.podUid().equals(target.podUid()) + || !acceptance + .actualPodEndpoint() + .equals(target.exactPodEndpoint().orElseThrow().toString()) + || !acceptance.image().equals(target.image()) + || !acceptance.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !acceptance.actualServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !acceptance.actualPeerSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow()) + || !acceptance.jti().equals(entry.jti()) + || !acceptance.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || acceptance.result() != target.expectation() + || !entry.targetKid().equals(acceptance.verifiedKid())) { + throw new IdempotencyConflictException( + "Authenticated receiver evidence differs from the exact protected Pod target"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + PodReceipt candidate = + podReceipt( + entry, + persistedPod, + acceptance, + alreadyVerified ? entry.entryVersion() - 1L : entry.entryVersion()); + PodReceipt existing = selectPodReceipt(candidate, true); + if (alreadyVerified) { + List retainedReceipts = selectPodReceipts(entry, true); + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, retainedReceipts); + if (existing == null + || !existing.equals(candidate) + || retainedReceipts.size() != expectedPods.size() + || entry.verificationReceipt().filter(recomputed::equals).isEmpty()) { + throw new IdempotencyConflictException( + "A completed readiness Pod receipt retry differs from its immutable evidence"); + } + return entry; + } + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "A per-Pod readiness receipt already exists with different evidence"); + } + } else { + insertPodReceipt(candidate); + PodReceipt readback = selectPodReceipt(candidate, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Readiness Pod receipt did not read back exactly"); + } + } + + List receipts = selectPodReceipts(entry, true); + if (receipts.size() != expectedPods.size()) { + if (receipts.size() > expectedPods.size()) { + throw new QuarantinedStateException("Readiness Pod receipt set exceeds its exact target"); + } + ProbeEntry partial = selectEntry(entry, true); + if (partial == null || partial.state() != ProbeState.ISSUED) { + throw new QuarantinedStateException("Partial per-Pod receipt changed its logical entry"); + } + return partial; + } + VerificationReceipt closure = podReceiptClosure(plan, entry, expectedPods, receipts); + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt finalReceipt = + new VerificationReceipt( + closure.receiptVersion(), + entry.entryVersion(), + resultEntryVersion, + closure.observedAtEpochSecond(), + closure.receiptSha256(), + closure.verifiedKid(), + closure.validatorInstanceId(), + closure.validatorBindingDigest(), + closure.validatorConfigRevision(), + closure.validatorPeerUri(), + closure.validatorPeerSpkiSha256(), + closure.podReceiptCount(), + closure.podReceiptClosureSha256()); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ?, " + + "pod_receipt_count = ?, pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND entry_plan_version = 2 AND state = 'ISSUED' AND entry_version = ? " + + "AND target_generation = ? AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + finalReceipt.resultEntryVersion(), + finalReceipt.receiptVersion(), + finalReceipt.sourceEntryVersion(), + finalReceipt.observedAtEpochSecond(), + finalReceipt.verifiedKid(), + finalReceipt.validatorInstanceId(), + finalReceipt.validatorBindingDigest(), + finalReceipt.validatorConfigRevision(), + finalReceipt.validatorPeerUri(), + finalReceipt.validatorPeerSpkiSha256(), + finalReceipt.receiptSha256(), + finalReceipt.podReceiptCount(), + finalReceipt.podReceiptClosureSha256(), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.jti(), + entry.planDigest(), + entry.entryVersion(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.compactTokenSha256().orElseThrow()); + if (changed != 1) { + throw new VersionConflictException("Readiness per-Pod closure lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != finalReceipt.resultEntryVersion() + || readback.verificationReceipt().filter(finalReceipt::equals).isEmpty()) { + throw new QuarantinedStateException("Readiness per-Pod closure did not read back exactly"); + } + return readback; + } + + private List selectExpectedPods(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + EXPECTED_POD_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR KEY SHARE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List expected = new ArrayList<>(rows.size()); + for (Record row : rows) { + String endpoint = row.get("exact_pod_endpoint", String.class); + expected.add( + new ExpectedPod( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + new PodTarget( + row.get("inventory_snapshot_digest", String.class), + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + row.get("validator_id", String.class), + row.get("deployment_uid", UUID.class).toString(), + row.get("pod_uid", UUID.class).toString(), + row.get("pod_ip", String.class), + row.get("image", String.class), + row.get("verifier_config_sha256", String.class), + row.get("applicability_matrix_digest", String.class), + ProbeExpectation.valueOf(row.get("expected_outcome", String.class)), + Optional.ofNullable(endpoint).map(URI::create), + Optional.ofNullable(row.get("canonical_service_uri", String.class)), + Optional.ofNullable(row.get("expected_pod_leaf_spki_sha256", String.class))))); + } + return List.copyOf(expected); + } + + private void requireLiveInventoryMatches( + ReadinessProbePlan plan, + Binding binding, + TrustFence trust, + InventorySnapshot liveInventory, + ObservationContext expectedContext) { + Objects.requireNonNull(liveInventory, "Fresh protected live inventory is required"); + requireFreshLiveInventory(liveInventory); + String expectedDigest = + plan.inventorySnapshotDigest().orElseThrow(ReceiverUnavailableException::new); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.readRequired(expectedDigest, binding, trust); + if (liveInventory.observationContext().filter(expectedContext::equals).isEmpty() + || !expectedDigest.equals(liveInventory.digest()) + || !stored.digest().equals(liveInventory.digest()) + || !stored.environmentId().equals(liveInventory.environmentId()) + || !stored.clusterId().equals(liveInventory.clusterId()) + || !stored.clusterIncarnationUid().equals(liveInventory.clusterIncarnationUid()) + || !stored.namespace().equals(liveInventory.namespace()) + || !stored.namespaceUid().equals(liveInventory.namespaceUid()) + || !stored.apiBindingRevision().equals(liveInventory.apiBindingRevision()) + || !stored.apiBindingDigest().equals(liveInventory.apiBindingDigest()) + || !stored.inventoryBindingRevision().equals(liveInventory.inventoryBindingRevision()) + || !stored.inventoryBindingDigest().equals(liveInventory.inventoryBindingDigest()) + || !MessageDigest.isEqual(stored.canonicalBytes(), liveInventory.canonicalBytes())) { + throw new ReceiverUnavailableException(); + } + } + + private static void requireObservationContext( + CurrentEvidence current, InventorySnapshot snapshot) { + if (snapshot.observationContext().filter(observationContext(current)::equals).isEmpty()) { + throw new InventoryPlanConflictException(); + } + } + + private static ObservationContext observationContext(CurrentEvidence current) { + return observationContext( + current.request().operationId(), + current.request().operationDigest(), + new SignerFence(current.state().durableActive(), current.state().publishedActive())); + } + + private static ObservationContext observationContext( + UUID operationId, String operationDigest, SignerFence expectedFence) { + if (!expectedFence.durableActive().equals(expectedFence.publishedActive())) { + throw new StaleOperationException("JWT active signer fence changed during inventory proof"); + } + ObservationPurpose purpose = + expectedFence.durableActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY; + return new ObservationContext(purpose, operationId, operationDigest); + } + + private void requireFreshLiveInventory(InventorySnapshot snapshot) { + long observedAt = snapshot.observedAt().getEpochSecond(); + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new StorageUnavailableException("Account validator inventory clock is unavailable"); + } + if (observedAt <= 0L + || observedAt > databaseNow + || databaseNow - observedAt > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new ReceiverUnavailableException(); + } + } + + private boolean hasCompletePodReceiptClosure(ReadinessProbePlan plan) { + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + return false; + } + int totalReceipts = 0; + for (ProbeEntry entry : plan.entries()) { + if (entry.state() != ProbeState.VERIFIED) { + return false; + } + VerificationReceipt receipt = entry.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2) { + throw new QuarantinedStateException( + "V2 readiness entry has no per-Pod verification closure receipt"); + } + List expectedPods = selectExpectedPods(entry, true); + List podReceipts = selectPodReceipts(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() != receipt.podReceiptCount()) { + throw new QuarantinedStateException( + "V2 readiness receipt count differs from its exact expected Pod inventory"); + } + if (podReceipts.size() < expectedPods.size()) { + return false; + } + if (podReceipts.size() != expectedPods.size()) { + throw new QuarantinedStateException( + "V2 readiness receipt set exceeds its exact expected Pod inventory"); + } + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, podReceipts); + if (!recomputed.equals(receipt)) { + throw new QuarantinedStateException( + "V2 readiness entry closure differs from retained per-Pod receipts"); + } + totalReceipts = Math.addExact(totalReceipts, podReceipts.size()); + if (totalReceipts > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure exceeds its bound"); + } + } + return totalReceipts > 0; + } + + private void insertPodReceipt(PodReceipt receipt) { + dsl.execute( + "INSERT INTO " + + POD_RECEIPT_TABLE + + " (rotation_operation_id, plan_digest, validator_id, token_profile, audience, " + + "probe_kind, pod_uid, receipt_version, jti, source_entry_version, " + + "compact_token_sha256, target_generation, target_kid, expected_active_generation, " + + "expected_active_kid, outcome, observed_pod_uid, observed_image, " + + "observed_verifier_config_sha256, verified_kid, receiver_endpoint, " + + "receiver_service_uri, receiver_peer_spki_sha256, observed_at_epoch_seconds, receipt_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) " + + "DO NOTHING", + receipt.rotationOperationId(), + receipt.planDigest(), + receipt.validatorId(), + receipt.tokenProfile(), + receipt.audience(), + receipt.probeKind().name(), + UUID.fromString(receipt.podUid()), + 1, + receipt.jti(), + receipt.sourceEntryVersion(), + receipt.compactTokenSha256(), + Long.parseLong(receipt.targetGeneration()), + receipt.targetKid(), + receipt.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + receipt.expectedActive().map(ActiveSigner::kid).orElse(null), + receipt.outcome().name(), + UUID.fromString(receipt.observedPodUid()), + receipt.image(), + receipt.verifierConfigSha256(), + receipt.verifiedKid(), + receipt.receiverEndpoint().toString(), + receipt.receiverServiceUri(), + receipt.receiverPeerSpkiSha256(), + receipt.observedAtEpochSecond(), + receipt.receiptSha256()); + } + + private PodReceipt selectPodReceipt(PodReceipt key, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND pod_uid = ?" + + (lock ? " FOR UPDATE" : ""), + key.rotationOperationId(), + key.validatorId(), + key.tokenProfile(), + key.audience(), + key.probeKind().name(), + UUID.fromString(key.podUid())); + return row == null ? null : decodePodReceipt(row); + } + + private List selectPodReceipts(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR UPDATE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List receipts = new ArrayList<>(rows.size()); + for (Record row : rows) { + receipts.add(decodePodReceipt(row)); + } + return List.copyOf(receipts); + } + + private static PodReceipt decodePodReceipt(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + PodReceipt receipt = + new PodReceipt( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("pod_uid", UUID.class).toString(), + row.get("jti", UUID.class), + row.get("source_entry_version", Long.class), + row.get("compact_token_sha256", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + ProbeExpectation.valueOf(row.get("outcome", String.class)), + row.get("observed_pod_uid", UUID.class).toString(), + row.get("observed_image", String.class), + row.get("observed_verifier_config_sha256", String.class), + row.get("verified_kid", String.class), + URI.create(row.get("receiver_endpoint", String.class)), + row.get("receiver_service_uri", String.class), + row.get("receiver_peer_spki_sha256", String.class), + row.get("observed_at_epoch_seconds", Long.class), + row.get("receipt_sha256", String.class)); + if (!receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException("Immutable per-Pod readiness receipt digest is invalid"); + } + return receipt; + } + + private static PodReceipt podReceipt( + ProbeEntry entry, + ExpectedPod expected, + AuthenticatedAcceptance acceptance, + long sourceEntryVersion) { + PodTarget target = expected.target(); + PodReceipt unsigned = + new PodReceipt( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.podUid(), + entry.jti(), + sourceEntryVersion, + entry.compactTokenSha256().orElseThrow(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + acceptance.result(), + acceptance.podUid(), + acceptance.image(), + acceptance.verifierConfigSha256(), + acceptance.verifiedKid(), + URI.create(acceptance.actualPodEndpoint()), + acceptance.actualServiceUri(), + acceptance.actualPeerSpkiSha256(), + acceptance.observedAtEpochSecond(), + "0".repeat(64)); + return new PodReceipt( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.validatorId(), + unsigned.tokenProfile(), + unsigned.audience(), + unsigned.probeKind(), + unsigned.podUid(), + unsigned.jti(), + unsigned.sourceEntryVersion(), + unsigned.compactTokenSha256(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.outcome(), + unsigned.observedPodUid(), + unsigned.image(), + unsigned.verifierConfigSha256(), + unsigned.verifiedKid(), + unsigned.receiverEndpoint(), + unsigned.receiverServiceUri(), + unsigned.receiverPeerSpkiSha256(), + unsigned.observedAtEpochSecond(), + podReceiptDigest(unsigned)); + } + + private static ProbeEntry sourceEntryForVerifiedClosure(ProbeEntry verified) { + VerificationReceipt receipt = verified.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2 + || receipt.sourceEntryVersion() + 1L != verified.entryVersion()) { + throw new QuarantinedStateException("Verified per-Pod closure has an invalid source version"); + } + return new ProbeEntry( + verified.rotationOperationId(), + verified.planDigest(), + verified.validatorId(), + verified.tokenProfile(), + verified.audience(), + verified.probeKind(), + verified.jti(), + verified.targetGeneration(), + verified.targetKid(), + verified.expectedActive(), + verified.registryVersion(), + receipt.sourceEntryVersion(), + verified.plannedIssuedAtEpochSecond(), + verified.expiresAtEpochSecond(), + ProbeState.ISSUED, + Optional.empty(), + verified.signingAttemptedAtEpochSecond(), + verified.compactTokenSha256(), + Optional.empty()); + } + + private static String podReceiptDigest(PodReceipt receipt) { + Map value = new LinkedHashMap<>(); + value.put("domain", "account-jwt-readiness-per-pod-receipt/v1"); + value.put("rotationOperationId", receipt.rotationOperationId().toString()); + value.put("planDigest", receipt.planDigest()); + value.put("validatorId", receipt.validatorId()); + value.put("tokenProfile", receipt.tokenProfile()); + value.put("audience", receipt.audience()); + value.put("probeKind", receipt.probeKind().name()); + value.put("podUid", receipt.podUid()); + value.put("jti", receipt.jti().toString()); + value.put("sourceEntryVersion", receipt.sourceEntryVersion()); + value.put("compactTokenSha256", receipt.compactTokenSha256()); + value.put("targetGeneration", receipt.targetGeneration()); + value.put("targetKid", receipt.targetKid()); + value.put("expectedActive", activeMap(receipt.expectedActive())); + value.put("outcome", receipt.outcome().name()); + value.put("observedPodUid", receipt.observedPodUid()); + value.put("image", receipt.image()); + value.put("verifierConfigSha256", receipt.verifierConfigSha256()); + value.put("verifiedKid", receipt.verifiedKid()); + value.put("receiverEndpoint", receipt.receiverEndpoint().toString()); + value.put("receiverServiceUri", receipt.receiverServiceUri()); + value.put("receiverPeerSpkiSha256", receipt.receiverPeerSpkiSha256()); + value.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + return digest(value); + } + + private static VerificationReceipt podReceiptClosure( + ReadinessProbePlan plan, + ProbeEntry entry, + List expectedPods, + List receipts) { + Map expectedByUid = new LinkedHashMap<>(); + for (ExpectedPod expected : expectedPods) { + if (expectedByUid.putIfAbsent(expected.target().podUid(), expected) != null) { + throw new QuarantinedStateException("Readiness Pod plan contains duplicate Pod UIDs"); + } + } + Map receiptsByUid = new LinkedHashMap<>(); + for (PodReceipt receipt : receipts) { + ExpectedPod expected = expectedByUid.get(receipt.podUid()); + if (expected == null + || receiptsByUid.putIfAbsent(receipt.podUid(), receipt) != null + || !receipt.rotationOperationId().equals(entry.rotationOperationId()) + || !receipt.planDigest().equals(entry.planDigest()) + || !receipt.validatorId().equals(entry.validatorId()) + || !receipt.tokenProfile().equals(entry.tokenProfile()) + || !receipt.audience().equals(entry.audience()) + || receipt.probeKind() != entry.probeKind() + || !receipt.jti().equals(entry.jti()) + || receipt.sourceEntryVersion() != entry.entryVersion() + || !receipt.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || !receipt.targetGeneration().equals(entry.targetGeneration()) + || !receipt.targetKid().equals(entry.targetKid()) + || !receipt.expectedActive().equals(entry.expectedActive()) + || receipt.outcome() != expected.target().expectation() + || !receipt.observedPodUid().equals(expected.target().podUid()) + || !receipt.image().equals(expected.target().image()) + || !receipt.verifierConfigSha256().equals(expected.target().verifierConfigSha256()) + || !receipt.receiverEndpoint().equals(expected.target().exactPodEndpoint().orElseThrow()) + || !receipt + .receiverServiceUri() + .equals(expected.target().canonicalServiceUri().orElseThrow()) + || !receipt + .receiverPeerSpkiSha256() + .equals(expected.target().podLeafSpkiSha256().orElseThrow()) + || !receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException( + "Readiness Pod receipt does not match its exact target"); + } + } + if (expectedByUid.size() != receiptsByUid.size() + || expectedByUid.isEmpty() + || expectedByUid.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure is incomplete"); + } + ProbeExpectation expectedOutcome = null; + List> closurePods = new ArrayList<>(); + List ordered = + expectedPods.stream() + .sorted(java.util.Comparator.comparing(value -> value.target().podUid())) + .toList(); + long observedAt = 0L; + for (ExpectedPod expected : ordered) { + PodTarget target = expected.target(); + PodReceipt receipt = receiptsByUid.get(target.podUid()); + if (receipt == null || (expectedOutcome != null && expectedOutcome != target.expectation())) { + throw new QuarantinedStateException("Readiness Pod expectations are not a closed matrix"); + } + expectedOutcome = target.expectation(); + observedAt = Math.max(observedAt, receipt.observedAtEpochSecond()); + Map pod = new LinkedHashMap<>(); + pod.put("podUid", target.podUid()); + pod.put("podIpEndpoint", target.exactPodEndpoint().orElseThrow().toString()); + pod.put("serviceUri", target.canonicalServiceUri().orElseThrow()); + pod.put("leafSpkiSha256", target.podLeafSpkiSha256().orElseThrow()); + pod.put("image", target.image()); + pod.put("verifierConfigSha256", target.verifierConfigSha256()); + pod.put("receiptSha256", receipt.receiptSha256()); + closurePods.add(pod); + } + ExpectedPod first = ordered.get(0); + PodTarget firstTarget = first.target(); + Map closure = new LinkedHashMap<>(); + closure.put("domain", "account-jwt-readiness-per-pod-closure/v1"); + closure.put("rotationOperationId", plan.operationId().toString()); + closure.put("planDigest", plan.planDigest()); + closure.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + closure.put("inventorySnapshotDigest", plan.inventorySnapshotDigest().orElseThrow()); + closure.put("validatorId", entry.validatorId()); + closure.put("tokenProfile", entry.tokenProfile()); + closure.put("audience", entry.audience()); + closure.put("probeKind", entry.probeKind().name()); + closure.put("jti", entry.jti().toString()); + closure.put("sourceEntryVersion", entry.entryVersion()); + closure.put("compactTokenSha256", entry.compactTokenSha256().orElseThrow()); + closure.put("targetGeneration", entry.targetGeneration()); + closure.put("targetKid", entry.targetKid()); + closure.put("expectedActive", activeMap(entry.expectedActive())); + closure.put("pods", closurePods); + String closureSha256 = digest(closure); + return new VerificationReceipt( + 2, + entry.entryVersion(), + entry.entryVersion() + 1L, + observedAt, + closureSha256, + entry.targetKid(), + firstTarget.podUid(), + firstTarget.inventoryBindingDigest(), + firstTarget.inventoryBindingRevision(), + firstTarget.canonicalServiceUri().orElseThrow(), + firstTarget.podLeafSpkiSha256().orElseThrow(), + expectedPods.size(), + closureSha256); + } + + private ReadinessProbePlan selectPlan(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PLAN_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodePlan(row, selectEntries(operationId, lock)); + } + + private ReadinessProbePlan readbackPlan(ReadinessProbePlan plan, boolean lock) { + List entries = selectEntries(plan.operationId(), lock); + if (!entries.equals(plan.entries())) { + throw new QuarantinedStateException("Readiness probe entries changed after plan persistence"); + } + if (!plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException("Readiness probe plan digest is invalid"); + } + plan.inventorySnapshotDigest() + .ifPresent( + digest -> inventoryRepository.readRequired(digest, plan.binding(), plan.trustFence())); + return plan; + } + + private List selectEntries(UUID operationId, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? ORDER BY validator_id, CASE token_profile WHEN '" + + CANARY_PROFILE + + "' THEN 0 WHEN '" + + CONTROL_UI_PROFILE + + "' THEN 1 WHEN '" + + PLAYER_BOOTSTRAP_PROFILE + + "' THEN 2 WHEN '" + + REPRESENTATIVE_PROFILE + + "' THEN 3 ELSE 4 END, token_profile, audience, probe_kind" + + (lock ? " FOR UPDATE" : ""), + operationId); + List entries = new ArrayList<>(rows.size()); + for (Record row : rows) { + entries.add(decodeEntry(row)); + } + return List.copyOf(entries); + } + + // V1 digests bind the established canary/control/player/delegation profile order. V2 adds + // validator identity as the leading key; per-Pod requirements remain separately bound rows. + private static final Comparator PROBE_ENTRY_ORDER = + Comparator.comparing(ProbeEntry::validatorId) + .thenComparingInt(entry -> profileOrder(entry.tokenProfile())) + .thenComparing(ProbeEntry::audience) + .thenComparing(entry -> entry.probeKind().name()); + + private static int profileOrder(String profile) { + if (CANARY_PROFILE.equals(profile)) return 0; + if (CONTROL_UI_PROFILE.equals(profile)) return 1; + if (PLAYER_BOOTSTRAP_PROFILE.equals(profile)) return 2; + if (REPRESENTATIVE_PROFILE.equals(profile)) return 3; + throw new QuarantinedStateException("Readiness probe profile has no canonical plan order"); + } + + private ProbeEntry selectEntry( + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ?" + + (lock ? " FOR UPDATE" : ""), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name()); + return row == null ? null : decodeEntry(row); + } + + private ProbeEntry selectEntry(ProbeEntry entry, boolean lock) { + return selectEntry( + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + lock); + } + + private ProbeEntry decodeEntry(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Optional expectedActive = decodeActive(activeGeneration, activeKid); + Long attemptAt = row.get("signing_attempted_at_epoch_seconds", Long.class); + String hash = row.get("compact_token_sha256", String.class); + String terminalOutcome = row.get("terminal_outcome", String.class); + VerificationReceipt receipt = decodeVerificationReceipt(row); + return new ProbeEntry( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + expectedActive, + row.get("registry_version", Short.class).intValue(), + row.get("entry_version", Long.class), + row.get("planned_issued_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + ProbeState.valueOf(row.get("state", String.class)), + Optional.ofNullable(terminalOutcome), + Optional.ofNullable(attemptAt), + Optional.ofNullable(hash), + Optional.ofNullable(receipt)); + } + + private VerificationReceipt decodeVerificationReceipt(Record row) { + Short version = row.get("verification_receipt_version", Short.class); + Long sourceVersion = row.get("verification_source_entry_version", Long.class); + Long verifiedAt = row.get("verified_at_epoch_seconds", Long.class); + String verifiedKid = row.get("verified_kid", String.class); + String validatorInstanceId = row.get("validator_instance_id", String.class); + String bindingDigest = row.get("validator_binding_digest", String.class); + String configRevision = row.get("validator_config_revision", String.class); + String peerUri = row.get("validator_peer_uri", String.class); + String peerSpki = row.get("validator_peer_spki_sha256", String.class); + String receiptSha256 = row.get("verification_receipt_sha256", String.class); + Short podReceiptCount = row.get("pod_receipt_count", Short.class); + String podReceiptClosureSha256 = row.get("pod_receipt_closure_sha256", String.class); + if (version == null + && sourceVersion == null + && verifiedAt == null + && verifiedKid == null + && validatorInstanceId == null + && bindingDigest == null + && configRevision == null + && peerUri == null + && peerSpki == null + && receiptSha256 == null + && podReceiptCount == null + && podReceiptClosureSha256 == null) { + return null; + } + if (version == null + || sourceVersion == null + || verifiedAt == null + || validatorInstanceId == null + || bindingDigest == null + || configRevision == null + || peerUri == null + || peerSpki == null + || receiptSha256 == null) { + throw new QuarantinedStateException("Readiness verification receipt is partial"); + } + if ((version == 1 + && (verifiedKid == null || podReceiptCount != null || podReceiptClosureSha256 != null)) + || (version == 2 && (podReceiptCount == null || podReceiptClosureSha256 == null))) { + throw new QuarantinedStateException("Readiness verification receipt version is partial"); + } + Long resultVersion = Math.addExact(sourceVersion, 1L); + return new VerificationReceipt( + version.intValue(), + sourceVersion, + resultVersion, + verifiedAt, + receiptSha256, + verifiedKid, + validatorInstanceId, + bindingDigest, + configRevision, + peerUri, + peerSpki, + podReceiptCount == null ? 0 : podReceiptCount.intValue(), + podReceiptClosureSha256); + } + + private ReadinessProbePlan decodePlan(Record row, List entries) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Long publishedGeneration = row.get("expected_published_generation", Long.class); + String publishedKid = row.get("expected_published_kid", String.class); + SignerFence fence = + new SignerFence( + decodeActive(activeGeneration, activeKid), + decodeActive(publishedGeneration, publishedKid)); + return new ReadinessProbePlan( + row.get("rotation_operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("desired_state_version", Long.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + row.get("target_public_key_fingerprint", String.class), + fence, + row.get("publication_intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("applicability_matrix_json", String.class), + row.get("applicability_matrix_digest", String.class), + row.get("validator_inventory_complete", Boolean.class), + row.get("maximum_cache_age_seconds", Short.class).intValue(), + row.get("planned_at_epoch_seconds", Long.class), + row.get("not_before_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("plan_version", Short.class).intValue(), + row.get("plan_digest", String.class), + entries, + Optional.ofNullable(row.get("inventory_snapshot_digest", String.class))); + } + + private static Optional decodeActive(Long generation, String kid) { + if (generation == null && kid == null) { + return Optional.empty(); + } + if (generation == null || kid == null) { + throw new QuarantinedStateException("Readiness signer fence has a partial active pair"); + } + return Optional.of(new ActiveSigner(generation.toString(), kid)); + } + + private void requirePlanMatchesCurrent(ReadinessProbePlan plan, CurrentEvidence current) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence().orElseThrow(); + if (!plan.operationId().equals(request.operationId()) + || !plan.binding().equals(request.binding()) + || !plan.trustFence().equals(request.trustFence()) + || !plan.operationDigest().equals(request.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(request.expectedActive()) + || !plan.expectedFence().publishedActive().equals(request.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || (plan.planVersion() == 1 + && !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson())) + || !plan.applicabilityMatrixDigest() + .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) + || (plan.planVersion() == 1 && plan.validatorInventoryComplete()) + || (plan.planVersion() == INVENTORY_PLAN_VERSION && !matchesStoredV2Inventory(plan)) + || !plan.planDigest().equals(planDigest(plan))) { + throw new StaleOperationException( + "Readiness probe plan no longer matches current Account evidence"); + } + } + + private static AccountJwtJwksPublicationRepository.PromotionPublicationEvidence + promotionPublicationEvidence( + AccountJwtJwksPublicationRepository.PublicationEvidence publication) { + return new AccountJwtJwksPublicationRepository.PromotionPublicationEvidence( + publication.intent(), + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()), + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException())); + } + + private boolean matchesStoredV2Inventory(ReadinessProbePlan plan) { + String inventoryDigest = plan.inventorySnapshotDigest().orElse(null); + if (inventoryDigest == null) { + return false; + } + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + inventoryRepository.readRequired(inventoryDigest, plan.binding(), plan.trustFence()); + try { + JsonNode matrix = JSON.readTree(plan.applicabilityMatrixJson()); + JsonNode source = matrix == null ? null : matrix.get("source"); + if (matrix == null + || !matrix.isObject() + || !"2".equals(matrix.path("schemaVersion").asText()) + || !inventoryDigest.equals(matrix.path("inventorySnapshotDigest").asText()) + || source == null + || !snapshot.apiBindingRevision().equals(source.path("apiBindingRevision").asText()) + || !snapshot.apiBindingDigest().equals(source.path("apiBindingDigest").asText()) + || !snapshot + .inventoryBindingRevision() + .equals(source.path("inventoryBindingRevision").asText()) + || !snapshot + .inventoryBindingDigest() + .equals(source.path("inventoryBindingDigest").asText()) + || !snapshot.clusterIncarnationUid().equals(source.path("clusterIncarnationUid").asText()) + || !snapshot.namespace().equals(source.path("namespace").asText()) + || !snapshot.namespaceUid().equals(source.path("namespaceUid").asText()) + || !snapshot.environmentId().equals(source.path("environmentId").asText()) + || !snapshot.clusterId().equals(source.path("clusterId").asText())) { + return false; + } + JsonNode validators = matrix.get("validators"); + if (validators == null + || !validators.isArray() + || validators.isEmpty() + || validators.size() > 32) { + return false; + } + if (!plan.validatorInventoryComplete()) { + return "PARTIAL_UNCONFIRMED".equals(matrix.path("inventoryStatus").asText()); + } + if (!"PROTECTED_LIVE_COMPLETE".equals(matrix.path("inventoryStatus").asText()) + || validators.size() != 2) { + return false; + } + JsonNode accountProfiles = null; + JsonNode gameSessionProfiles = null; + for (JsonNode validator : validators) { + String validatorId = validator.path("validatorId").asText(); + if (VALIDATOR_ID.equals(validatorId)) { + accountProfiles = validator.get("applicableProfiles"); + } else if ("game-session-service".equals(validatorId)) { + gameSessionProfiles = validator.get("applicableProfiles"); + } else { + return false; + } + } + return hasExactProfiles(accountProfiles, PRODUCTION_PROFILE_CASES) + && hasExactProfiles( + gameSessionProfiles, + List.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } catch (Exception failure) { + throw new QuarantinedStateException("V2 readiness inventory matrix cannot be read back"); + } + } + + private static boolean hasExactProfiles(JsonNode node, List expected) { + if (node == null || !node.isArray() || node.size() != expected.size()) { + return false; + } + Set actual = new java.util.HashSet<>(); + for (JsonNode profile : node) { + actual.add( + new ProfileCase( + profile.path("tokenProfile").asText(), profile.path("audience").asText())); + } + return actual.equals(Set.copyOf(expected)); + } + + private static void requirePreparedPlanMatches( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication) { + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = publication.receipt(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence(); + if (!plan.operationId().equals(generation.operationId()) + || !plan.binding().equals(generation.binding()) + || !plan.trustFence().equals(generation.trustFence()) + || !plan.operationDigest().equals(generation.operationDigest()) + || !plan.generationRequestDigest().equals(generation.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generation.receiptDigest()) + || plan.desiredStateVersion() != generation.desiredStateVersion() + || !plan.targetGeneration().equals(generation.targetGeneration()) + || !plan.targetKid().equals(generation.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(promotion.expectedPreviousActive()) + || !plan.expectedFence().publishedActive().equals(promotion.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || !plan.planDigest().equals(promotion.readinessPlanDigest()) + || !intent.operationId().equals(generation.operationId()) + || !receipt.operationId().equals(generation.operationId()) + || !mount.operationId().equals(generation.operationId()) + || !promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Prepared readiness evidence differs from exact Account generation/publication owner records"); + } + } + + private CurrentEvidence lockCurrentEvidence(Binding binding, TrustFence trust) { + Objects.requireNonNull(binding, "Account signer binding is required"); + Objects.requireNonNull(trust, "Current signer trust fence is required"); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + DesiredState state = desiredStateRepository.read(binding); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = + publicationRepository + .readCurrentPublication(binding, trust) + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (request.phase() != GenerationPhase.GENERATION_RECORDED + || state.preparedOperationId().isPresent() + || !state.generationOperationId().equals(Optional.of(request.operationId())) + || !request.operationId().equals(result.operationId()) + || !request.binding().equals(binding) + || !result.binding().equals(binding) + || !request.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || state.recordVersion() != result.desiredStateVersion() + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.expectedActive().equals(state.durableActive()) + || !request.expectedPublishedActive().equals(state.publishedActive()) + || !state.durableActive().equals(state.publishedActive())) { + throw new StaleOperationException( + "Current Account JWT signer evidence is incomplete or changed"); + } + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !receipt.operationId().equals(result.operationId()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !mount.operationId().equals(result.operationId()) + || !mount.intentDigest().equals(intent.intentDigest()) + || !mount.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !mount.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new StaleOperationException( + "Account JWT publication evidence is not exact for readiness"); + } + return new CurrentEvidence(state, request, result, publication); + } + + private ReadinessProbePlan requireStoredPlan(CurrentEvidence current) { + ReadinessProbePlan plan = selectPlan(current.request().operationId(), true); + if (plan == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(plan, current); + return readbackPlan(plan, true); + } + + private static void requireCurrentOperation(CurrentEvidence current, String operationId) { + if (!current.request().operationId().toString().equals(operationId)) { + throw new StaleOperationException("Readiness probe belongs to a stale Account operation"); + } + } + + private static void requireSignedResultMatches( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest signed) { + if (entry == null + || !signed.operationId().equals(plan.operationId().toString()) + || !signed.validatorId().equals(entry.validatorId()) + || signed.probeKind() != entry.probeKind() + || !signed.tokenProfile().equals(entry.tokenProfile()) + || !signed.audience().equals(entry.audience()) + || !signed.jti().equals(entry.jti()) + || !signed.targetGeneration().equals(entry.targetGeneration()) + || !signed.targetKid().equals(entry.targetKid()) + || !signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + || signed.issuedAtEpochSecond() != entry.plannedIssuedAtEpochSecond() + || signed.expiresAtEpochSecond() != entry.expiresAtEpochSecond() + || !SHA256.matcher(signed.compactTokenSha256()).matches()) { + throw new IdempotencyConflictException( + "Mounted readiness signature does not match its exact plan"); + } + } + + private static VerificationReceipt verificationReceipt( + ReadinessProbePlan plan, + ProbeEntry entry, + VerifiedProbeObservation observation, + long resultEntryVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("receiptVersion", 1); + fields.put("rotationOperationId", plan.operationId().toString()); + fields.put("planDigest", plan.planDigest()); + fields.put("operationDigest", plan.operationDigest()); + fields.put("generationRequestDigest", plan.generationRequestDigest()); + fields.put("generationReceiptDigest", plan.generationReceiptDigest()); + fields.put("desiredStateVersion", plan.desiredStateVersion()); + fields.put("environmentId", plan.binding().environmentId()); + fields.put("clusterId", plan.binding().clusterId()); + fields.put("namespace", plan.binding().namespace()); + fields.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + fields.put("targetGeneration", entry.targetGeneration()); + fields.put("targetKid", entry.targetKid()); + fields.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + fields.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + fields.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + fields.put("validatorId", entry.validatorId()); + fields.put("tokenProfile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probeKind", entry.probeKind().name()); + fields.put("jti", entry.jti().toString()); + fields.put("registryVersion", entry.registryVersion()); + fields.put("sourceEntryVersion", entry.entryVersion()); + fields.put("resultEntryVersion", resultEntryVersion); + fields.put("issuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + fields.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + fields.put("compactTokenSha256", observation.compactTokenSha256()); + fields.put("verifiedKid", observation.verifiedKid()); + fields.put("validatorInstanceId", observation.validatorInstanceId()); + fields.put("validatorBindingDigest", observation.validatorBindingDigest()); + fields.put("validatorConfigRevision", observation.validatorConfigRevision()); + fields.put("validatorPeerUri", observation.validatorPeerUri()); + fields.put("validatorPeerSpkiSha256", observation.validatorPeerSpkiSha256()); + fields.put("observedAtEpochSecond", observation.observedAtEpochSecond()); + return new VerificationReceipt( + 1, + entry.entryVersion(), + resultEntryVersion, + observation.observedAtEpochSecond(), + digest(fields), + observation.verifiedKid(), + observation.validatorInstanceId(), + observation.validatorBindingDigest(), + observation.validatorConfigRevision(), + observation.validatorPeerUri(), + observation.validatorPeerSpkiSha256()); + } + + private static void requireMatchingObservation( + VerificationReceipt receipt, VerifiedProbeObservation observation) { + if (!receipt.verifiedKid().equals(observation.verifiedKid()) + || !receipt.validatorInstanceId().equals(observation.validatorInstanceId()) + || !receipt.validatorBindingDigest().equals(observation.validatorBindingDigest()) + || !receipt.validatorConfigRevision().equals(observation.validatorConfigRevision()) + || !receipt.validatorPeerUri().equals(observation.validatorPeerUri()) + || !receipt.validatorPeerSpkiSha256().equals(observation.validatorPeerSpkiSha256())) { + throw new IdempotencyConflictException( + "Readiness verification retry differs from its immutable authenticated receipt"); + } + } + + private void requireNotExpired(ProbeEntry entry, long nowEpoch) { + if (nowEpoch >= entry.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + } + + static String applicabilityMatrixJson() { + List> applicableProfiles = + List.of( + Map.of("audience", CONTROL_UI_AUDIENCE, "tokenProfile", CONTROL_UI_PROFILE), + Map.of( + "audience", PLAYER_BOOTSTRAP_AUDIENCE, + "tokenProfile", PLAYER_BOOTSTRAP_PROFILE), + Map.of("audience", REPRESENTATIVE_AUDIENCE, "tokenProfile", REPRESENTATIVE_PROFILE)); + Map validator = new LinkedHashMap<>(); + validator.put("applicableProfiles", applicableProfiles); + validator.put("validatorId", VALIDATOR_ID); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", INVENTORY_STATUS); + matrix.put("schemaVersion", 1); + matrix.put("validators", List.of(validator)); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness applicability matrix cannot be canonicalized"); + } + } + + private static String applicabilityMatrixJson( + InventorySnapshot snapshot, boolean inventoryComplete) { + List> validators = + snapshot.validators().stream() + .sorted(java.util.Comparator.comparing(ValidatorObservation::validatorId)) + .map( + validator -> { + List> applicable = + validator.profiles().stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .sorted( + java.util.Comparator.comparing( + (Map value) -> + value.get("tokenProfile").toString()) + .thenComparing(value -> value.get("audience").toString())) + .toList(); + List> inapplicable = + PRODUCTION_PROFILE_CASES.stream() + .filter( + profile -> + validator.profiles().stream() + .noneMatch( + actual -> + actual.tokenProfile().equals(profile.tokenProfile()) + && actual.audience().equals(profile.audience()))) + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList(); + Map value = new LinkedHashMap<>(); + value.put("applicableProfiles", applicable); + value.put("deploymentUid", validator.deploymentUid()); + value.put("image", validator.image()); + value.put("podCount", validator.pods().size()); + value.put( + "pods", + validator.pods().stream() + .sorted(java.util.Comparator.comparing(PodObservation::uid)) + .map( + pod -> + Map.of( + "podUid", pod.uid(), + "podIp", pod.podIp(), + "exactPodEndpoint", pod.endpoint().toString(), + "canonicalServiceUri", pod.receiverServiceUri(), + "leafSpkiSha256", pod.leafSpkiSha256(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256())) + .toList()); + value.put("inapplicableProfiles", inapplicable); + value.put("validatorId", validator.validatorId()); + value.put("verifierConfigSha256", validator.verifierConfigSha256()); + return value; + }) + .toList(); + Map source = new LinkedHashMap<>(); + source.put("apiBindingDigest", snapshot.apiBindingDigest()); + source.put("apiBindingRevision", snapshot.apiBindingRevision()); + source.put("clusterIncarnationUid", snapshot.clusterIncarnationUid()); + source.put("environmentId", snapshot.environmentId()); + source.put("inventoryBindingDigest", snapshot.inventoryBindingDigest()); + source.put("inventoryBindingRevision", snapshot.inventoryBindingRevision()); + source.put("namespace", snapshot.namespace()); + source.put("namespaceUid", snapshot.namespaceUid()); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", inventoryComplete ? "PROTECTED_LIVE_COMPLETE" : INVENTORY_STATUS); + matrix.put("inventorySnapshotDigest", snapshot.digest()); + matrix.put( + "productionProfiles", + PRODUCTION_PROFILE_CASES.stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList()); + matrix.put("schemaVersion", INVENTORY_PLAN_VERSION); + matrix.put("source", source); + matrix.put("validators", validators); + try { + String canonical = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + if (canonical.getBytes(StandardCharsets.UTF_8).length > 8192) { + throw new InventoryPlanConflictException(); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness inventory applicability matrix cannot be canonicalized"); + } + } + + private static boolean inventoryPlanComplete(InventorySnapshot snapshot) { + Map> actual = new LinkedHashMap<>(); + for (ValidatorObservation validator : snapshot.validators()) { + Set profiles = new java.util.HashSet<>(); + for (var profile : validator.profiles()) { + ProfileCase candidate = new ProfileCase(profile.tokenProfile(), profile.audience()); + if (!PRODUCTION_PROFILE_CASES.contains(candidate) || !profiles.add(candidate)) { + return false; + } + } + if (validator.pods().isEmpty() + || actual.putIfAbsent(validator.validatorId(), profiles) != null) { + return false; + } + } + Set accountProfiles = actual.get(VALIDATOR_ID); + Set gameSessionProfiles = actual.get("game-session-service"); + return actual.keySet().equals(Set.of(VALIDATOR_ID, "game-session-service")) + && accountProfiles != null + && accountProfiles.equals(Set.copyOf(PRODUCTION_PROFILE_CASES)) + && gameSessionProfiles != null + && gameSessionProfiles.equals( + Set.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } + + private static List expectedPods( + ReadinessProbePlan plan, InventorySnapshot snapshot) { + List expected = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ValidatorObservation validator = + snapshot.validators().stream() + .filter(value -> value.validatorId().equals(entry.validatorId())) + .findFirst() + .orElseThrow(InventoryPlanConflictException::new); + ProbeExpectation expectation = + entry.probeKind() == ProbeKind.CANARY + ? ProbeExpectation.ACCEPT + : validator.profiles().stream() + .anyMatch( + profile -> + profile.tokenProfile().equals(entry.tokenProfile()) + && profile.audience().equals(entry.audience())) + ? ProbeExpectation.ACCEPT + : ProbeExpectation.INAPPLICABLE_REJECT; + for (PodObservation pod : validator.pods()) { + PodTarget target = + new PodTarget( + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + snapshot.clusterIncarnationUid(), + snapshot.namespace(), + snapshot.namespaceUid(), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + validator.validatorId(), + validator.deploymentUid(), + pod.uid(), + pod.podIp(), + pod.image(), + pod.verifierConfigSha256(), + plan.applicabilityMatrixDigest(), + expectation, + Optional.of(pod.endpoint()), + Optional.of(pod.receiverServiceUri()), + Optional.of(pod.leafSpkiSha256())); + expected.add( + new ExpectedPod( + plan.operationId(), + plan.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + target)); + } + } + if (expected.isEmpty() || expected.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(expected); + } + + private static String planDigest( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + int planVersion, + boolean validatorInventoryComplete, + long plannedAt, + long notBefore, + long expiresAt, + List entries, + Optional inventorySnapshotDigest) { + Map preimage = new LinkedHashMap<>(); + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + planVersion); + preimage.put("rotationOperationId", request.operationId().toString()); + preimage.put("environmentId", request.binding().environmentId()); + preimage.put("clusterId", request.binding().clusterId()); + preimage.put("namespace", request.binding().namespace()); + preimage.put("custodyMode", request.binding().mode().value()); + preimage.put("operationDigest", request.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("desiredStateVersion", result.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", request.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", request.trustFence().expectedNamespaceUid(), + "bindingDigest", request.trustFence().bindingDigest(), + "configRevision", request.trustFence().configRevision())); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedActive", activeMap(request.expectedActive())); + preimage.put("expectedPublishedActive", activeMap(request.expectedPublishedActive())); + preimage.put("publicationIntentDigest", publication.intent().intentDigest()); + preimage.put("publicationReceiptDigest", publication.receipt().orElseThrow().receiptDigest()); + preimage.put( + "mountedObservationDigest", + publication.mountedCorrespondence().orElseThrow().observationDigest()); + preimage.put("applicabilityMatrixJson", matrixJson); + preimage.put("applicabilityMatrixDigest", matrixDigest); + preimage.put("validatorInventoryComplete", validatorInventoryComplete); + if (planVersion != 1) { + preimage.put("planVersion", planVersion); + } + inventorySnapshotDigest.ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", MAX_VALIDATOR_CACHE_AGE_SECONDS); + preimage.put("plannedAtEpochSecond", plannedAt); + preimage.put("notBeforeEpochSecond", notBefore); + preimage.put("expiresAtEpochSecond", expiresAt); + preimage.put( + "entries", + entries.stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return digest(preimage); + } + + private static String planDigest(ReadinessProbePlan plan) { + Map preimage = planDigestMap(plan); + return digest(preimage); + } + + private static Map planDigestMap(ReadinessProbePlan plan) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + plan.planVersion()); + preimage.put("rotationOperationId", plan.operationId().toString()); + preimage.put("environmentId", plan.binding().environmentId()); + preimage.put("clusterId", plan.binding().clusterId()); + preimage.put("namespace", plan.binding().namespace()); + preimage.put("custodyMode", plan.binding().mode().value()); + preimage.put("operationDigest", plan.operationDigest()); + preimage.put("generationRequestDigest", plan.generationRequestDigest()); + preimage.put("generationReceiptDigest", plan.generationReceiptDigest()); + preimage.put("desiredStateVersion", plan.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + preimage.put("targetGeneration", plan.targetGeneration()); + preimage.put("targetKid", plan.targetKid()); + preimage.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + preimage.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + preimage.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + preimage.put("publicationIntentDigest", plan.publicationIntentDigest()); + preimage.put("publicationReceiptDigest", plan.publicationReceiptDigest()); + preimage.put("mountedObservationDigest", plan.mountedObservationDigest()); + preimage.put("applicabilityMatrixJson", plan.applicabilityMatrixJson()); + preimage.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + preimage.put("validatorInventoryComplete", plan.validatorInventoryComplete()); + if (plan.planVersion() != 1) { + preimage.put("planVersion", plan.planVersion()); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", plan.maximumCacheAgeSeconds()); + preimage.put("plannedAtEpochSecond", plan.plannedAtEpochSecond()); + preimage.put("notBeforeEpochSecond", plan.notBeforeEpochSecond()); + preimage.put("expiresAtEpochSecond", plan.expiresAtEpochSecond()); + preimage.put( + "entries", + plan.entries().stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return preimage; + } + + private static Map entryDigestMap(ProbeEntry entry) { + Map item = new LinkedHashMap<>(); + item.put("validatorId", entry.validatorId()); + item.put("tokenProfile", entry.tokenProfile()); + item.put("audience", entry.audience()); + item.put("probeKind", entry.probeKind().name()); + item.put("jti", entry.jti().toString()); + item.put("targetGeneration", entry.targetGeneration()); + item.put("targetKid", entry.targetKid()); + item.put("expectedActive", activeMap(entry.expectedActive())); + item.put("registryVersion", entry.registryVersion()); + item.put("entryVersion", 1); + item.put("plannedIssuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + item.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + return item; + } + + private static Map activeMap(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner signer = active.orElseThrow(); + return Map.of("present", true, "generation", signer.generation(), "kid", signer.kid()); + } + + private static String deliveryClaimDigest(DeliveryClaim claim) { + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", claim.rotationOperationId().toString()); + value.put("planDigest", claim.planDigest()); + value.put("expectedClusterUid", claim.expectedClusterUid()); + value.put("expectedNamespaceUid", claim.expectedNamespaceUid()); + value.put("materializerTrustBindingDigest", claim.materializerTrustBindingDigest()); + value.put("materializerTrustConfigRevision", claim.materializerTrustConfigRevision()); + value.put("targetGeneration", claim.targetGeneration()); + value.put("targetKid", claim.targetKid()); + value.put("expectedActive", activeMap(claim.expectedActive())); + value.put("readinessBindingDigest", claim.readinessBindingDigest()); + value.put("readinessConfigRevision", claim.readinessConfigRevision()); + value.put( + "readinessBindingValidUntilEpochSecond", claim.readinessBindingValidUntilEpochSecond()); + value.put("validatorId", claim.validatorId()); + value.put("validatorInstanceId", claim.validatorInstanceId()); + value.put("validatorPeerUri", claim.validatorPeerUri()); + value.put("validatorPeerSpkiSha256", claim.validatorPeerSpkiSha256()); + value.put("claimedAtEpochSecond", claim.claimedAtEpochSecond()); + value.put("expiresAtEpochSecond", claim.expiresAtEpochSecond()); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException failure) { + throw new StorageUnavailableException("Readiness delivery claim cannot be canonicalized"); + } + } + + private static String readinessPromotionDigest( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest, + List verifiedProbes) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-promotion-proof/v1"); + preimage.put("plan", planDigestMap(plan)); + preimage.put("planDigest", plan.planDigest()); + preimage.put("generation", generationEvidenceMap(generation)); + preimage.put("publication", promotionPublicationEvidenceMap(publication)); + preimage.put("inventoryEvidenceReference", inventoryEvidenceReference); + preimage.put("inventoryEvidenceDigest", inventoryEvidenceDigest); + preimage.put( + "verifiedProbes", + verifiedProbes.stream() + .map(AccountJwtReadinessProbeRepository::verifiedProbeEvidenceMap) + .toList()); + return digest(preimage); + } + + private static Map generationEvidenceMap(GenerationResult result) { + Map value = new LinkedHashMap<>(); + value.put("operationId", result.operationId().toString()); + value.put("environmentId", result.binding().environmentId()); + value.put("clusterId", result.binding().clusterId()); + value.put("namespace", result.binding().namespace()); + value.put("custodyMode", result.binding().mode().value()); + value.put("operationDigest", result.operationDigest()); + value.put("generationRequestDigest", result.generationRequestDigest()); + value.put("desiredStateVersion", result.desiredStateVersion()); + value.put("trustFence", trustFenceMap(result.trustFence())); + value.put("privateSecretName", result.privateSecretName()); + value.put("secretUid", result.secretUid()); + value.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + value.put("observedResourceVersion", result.observedResourceVersion()); + value.put("targetGeneration", result.targetGeneration()); + value.put("targetKid", result.targetKid()); + value.put("targetAlgorithm", result.targetAlgorithm()); + value.put("publicKeyFingerprint", result.publicKeyFingerprint()); + value.put("publicJwkJson", result.publicJwkJson()); + value.put("receiptDigest", result.receiptDigest()); + return value; + } + + private static Map trustFenceMap(TrustFence trust) { + return Map.of( + "clusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "namespaceUid", trust.expectedNamespaceUid(), + "bindingDigest", trust.bindingDigest(), + "configRevision", trust.configRevision()); + } + + private static Map promotionPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence evidence) { + var intent = evidence.intent(); + var receipt = evidence.receipt(); + var mount = evidence.mountedCorrespondence(); + Map intentValue = new LinkedHashMap<>(); + intentValue.put("operationId", intent.operationId().toString()); + intentValue.put("environmentId", intent.binding().environmentId()); + intentValue.put("clusterId", intent.binding().clusterId()); + intentValue.put("namespace", intent.binding().namespace()); + intentValue.put("operationDigest", intent.operationDigest()); + intentValue.put("generationRequestDigest", intent.generationRequestDigest()); + intentValue.put("generationReceiptDigest", intent.generationReceiptDigest()); + intentValue.put("desiredStateVersion", intent.desiredStateVersion()); + intentValue.put("trustFence", trustFenceMap(intent.trustFence())); + intentValue.put("apiBindingDigest", intent.apiBindingDigest()); + intentValue.put("apiConfigRevision", intent.apiConfigRevision()); + intentValue.put("configMapName", intent.configMapName()); + intentValue.put("configMapUid", intent.configMapUid()); + intentValue.put("expectedResourceVersion", intent.expectedResourceVersion()); + intentValue.put("expectedSnapshotDigest", intent.expectedSnapshotDigest()); + intentValue.put("targetGeneration", intent.targetGeneration()); + intentValue.put("targetKid", intent.targetKid()); + intentValue.put("publicKeyFingerprint", intent.publicKeyFingerprint()); + intentValue.put("expectedDurableActive", activeMap(intent.expectedDurableActive())); + intentValue.put("expectedPublishedActive", activeMap(intent.expectedPublishedActive())); + intentValue.put("publicDataDigest", intent.publicDataDigest()); + intentValue.put("generationMarkerDigest", intent.generationMarkerDigest()); + intentValue.put("intentDigest", intent.intentDigest()); + + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("operationId", receipt.operationId().toString()); + receiptValue.put("intentDigest", receipt.intentDigest()); + receiptValue.put("configMapUid", receipt.configMapUid()); + receiptValue.put("expectedResourceVersion", receipt.expectedResourceVersion()); + receiptValue.put("observedResourceVersion", receipt.observedResourceVersion()); + receiptValue.put("publicDataDigest", receipt.publicDataDigest()); + receiptValue.put("receiptDigest", receipt.receiptDigest()); + + Map mountValue = new LinkedHashMap<>(); + mountValue.put("operationId", mount.operationId().toString()); + mountValue.put("intentDigest", mount.intentDigest()); + mountValue.put("publicationReceiptDigest", mount.publicationReceiptDigest()); + mountValue.put("generationMarkerDigest", mount.generationMarkerDigest()); + mountValue.put("publicDataDigest", mount.publicDataDigest()); + mountValue.put("publicKeyFingerprint", mount.publicKeyFingerprint()); + mountValue.put("observationDigest", mount.observationDigest()); + return Map.of("intent", intentValue, "receipt", receiptValue, "mount", mountValue); + } + + private static Map verifiedProbeEvidenceMap(VerifiedProbeEvidence probe) { + VerificationReceipt receipt = probe.receipt(); + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", probe.rotationOperationId().toString()); + value.put("planDigest", probe.planDigest()); + value.put("validatorId", probe.validatorId()); + value.put("tokenProfile", probe.tokenProfile()); + value.put("audience", probe.audience()); + value.put("probeKind", probe.probeKind().name()); + value.put("jti", probe.jti().toString()); + value.put("targetGeneration", probe.targetGeneration()); + value.put("targetKid", probe.targetKid()); + value.put("expectedActive", activeMap(probe.expectedActive())); + value.put("registryVersion", probe.registryVersion()); + value.put("entryVersion", probe.entryVersion()); + value.put("plannedIssuedAtEpochSecond", probe.plannedIssuedAtEpochSecond()); + value.put("expiresAtEpochSecond", probe.expiresAtEpochSecond()); + value.put("compactTokenSha256", probe.compactTokenSha256()); + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("receiptVersion", receipt.receiptVersion()); + receiptValue.put("sourceEntryVersion", receipt.sourceEntryVersion()); + receiptValue.put("resultEntryVersion", receipt.resultEntryVersion()); + receiptValue.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + receiptValue.put("receiptSha256", receipt.receiptSha256()); + receiptValue.put("verifiedKid", receipt.verifiedKid()); + receiptValue.put("validatorInstanceId", receipt.validatorInstanceId()); + receiptValue.put("validatorBindingDigest", receipt.validatorBindingDigest()); + receiptValue.put("validatorConfigRevision", receipt.validatorConfigRevision()); + receiptValue.put("validatorPeerUri", receipt.validatorPeerUri()); + receiptValue.put("validatorPeerSpkiSha256", receipt.validatorPeerSpkiSha256()); + receiptValue.put("podReceiptCount", receipt.podReceiptCount()); + receiptValue.put("podReceiptClosureSha256", receipt.podReceiptClosureSha256()); + value.put("verificationReceipt", receiptValue); + return value; + } + + private static String digest(Map value) { + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException ex) { + throw new StorageUnavailableException("Readiness evidence cannot be canonicalized"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException("SHA-256 is unavailable"); + } + } + + private static long exactEpochSecond(Instant instant) { + Objects.requireNonNull(instant, "Readiness timestamp is required"); + if (instant.getNano() != 0 || instant.getEpochSecond() <= 0L) { + throw new IllegalArgumentException("Readiness time must be a positive exact epoch second"); + } + return instant.getEpochSecond(); + } + + private static long add(long value, long amount) { + try { + return Math.addExact(value, amount); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Readiness timestamp overflow", ex); + } + } + + private static void requireOperationId(UUID operationId) { + if (operationId == null || operationId.version() != 4 || operationId.variant() != 2) { + throw new IllegalArgumentException("Account JWT readiness operation ID must be UUIDv4"); + } + } + + private static String requireCanonicalKubeUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + String canonical = parsed.toString(); + if (!canonical.equals(value) + || parsed.equals(new UUID(0L, 0L)) + || parsed.version() < 1 + || parsed.version() > 8 + || parsed.variant() != 2) { + throw new IllegalArgumentException(); + } + return canonical; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + private static void insertOne(DSLContext dsl, String table, Map fields) { + String columns = String.join(", ", fields.keySet()); + String placeholders = String.join(", ", java.util.Collections.nCopies(fields.size(), "?")); + dsl.execute( + "INSERT INTO " + table + " (" + columns + ") VALUES (" + placeholders + ")", + fields.values().toArray()); + } + + private record CurrentEvidence( + DesiredState state, + GenerationRequest request, + GenerationResult result, + AccountJwtJwksPublicationRepository.PublicationEvidence publication) {} + + private record ProfileCase(String tokenProfile, String audience) {} + + /** Exact immutable per-Pod requirement for one logical registry entry. */ + public record ExpectedPod( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + PodTarget target) { + public ExpectedPod { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "expected Pod plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(target); + if (jti.version() != 4 || jti.variant() != 2 || !validatorId.equals(target.validatorId())) { + throw new QuarantinedStateException("Expected readiness Pod binding is malformed"); + } + } + } + + /** Owner-derived current plan, ISSUED entry, and exact expected Pod; contains no JWT. */ + public record OwnerProbeEvidence( + ReadinessProbePlan plan, ProbeEntry entry, ExpectedPod expectedPod) { + public OwnerProbeEvidence { + Objects.requireNonNull(plan); + Objects.requireNonNull(entry); + Objects.requireNonNull(expectedPod); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || entry.state() != ProbeState.ISSUED + || !plan.operationId().equals(entry.rotationOperationId()) + || !plan.planDigest().equals(entry.planDigest()) + || !entry.rotationOperationId().equals(expectedPod.rotationOperationId()) + || !entry.planDigest().equals(expectedPod.planDigest()) + || !entry.jti().equals(expectedPod.jti())) { + throw new ReceiverUnavailableException(); + } + } + } + + /** Immutable digest-covered one-Pod verifier receipt; no token or private key material. */ + private record PodReceipt( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + String podUid, + UUID jti, + long sourceEntryVersion, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActive, + ProbeExpectation outcome, + String observedPodUid, + String image, + String verifierConfigSha256, + String verifiedKid, + URI receiverEndpoint, + String receiverServiceUri, + String receiverPeerSpkiSha256, + long observedAtEpochSecond, + String receiptSha256) { + private PodReceipt { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "per-Pod readiness plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + requireCanonicalKubeUuid(podUid, "per-Pod readiness target UID"); + Objects.requireNonNull(jti); + if (jti.version() != 4 || jti.variant() != 2 || sourceEntryVersion <= 0L) { + throw new QuarantinedStateException("Per-Pod readiness receipt identity is malformed"); + } + requireDigest(compactTokenSha256, "per-Pod readiness token digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + Objects.requireNonNull(outcome); + requireCanonicalKubeUuid(observedPodUid, "observed readiness Pod UID"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new QuarantinedStateException("Per-Pod verifier image is not pinned"); + } + requireDigest(verifierConfigSha256, "per-Pod verifier config digest"); + if (verifiedKid == null || !verifiedKid.equals(targetKid)) { + throw new QuarantinedStateException("Per-Pod verifier outcome does not match its key ID"); + } + Objects.requireNonNull(receiverEndpoint); + requireDigest(receiverPeerSpkiSha256, "per-Pod receiver SPKI digest"); + if (receiverServiceUri == null + || !receiverServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Per-Pod receiver identity is malformed"); + } + requireDigest(receiptSha256, "per-Pod readiness receipt digest"); + } + } + + public enum ProbeState { + PLANNED, + ISSUED, + VERIFIED, + CLEANED, + EXPIRED, + ABORTED + } + + public record SignerFence( + Optional durableActive, Optional publishedActive) { + public SignerFence { + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Durable and published signer fences disagree"); + } + } + } + + public record ProbeEntry( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + ProbeState state, + Optional terminalOutcome, + Optional signingAttemptedAtEpochSecond, + Optional compactTokenSha256, + Optional verificationReceipt) { + public ProbeEntry { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "probe plan digest"); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(expectedActive); + Objects.requireNonNull(state); + terminalOutcome = Objects.requireNonNull(terminalOutcome); + signingAttemptedAtEpochSecond = Objects.requireNonNull(signingAttemptedAtEpochSecond); + compactTokenSha256 = Objects.requireNonNull(compactTokenSha256); + verificationReceipt = Objects.requireNonNull(verificationReceipt); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + requireGeneration(targetGeneration); + requireKid(targetKid); + if (jti.version() != 4 + || jti.variant() != 2 + || registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || expiresAtEpochSecond - plannedIssuedAtEpochSecond > PROBE_LIFETIME_SECONDS) { + throw new QuarantinedStateException("Readiness probe entry identity is malformed"); + } + compactTokenSha256.ifPresent(value -> requireDigest(value, "compact probe hash")); + if (compactTokenSha256.isPresent() != signingAttemptedAtEpochSecond.isPresent()) { + throw new QuarantinedStateException("Readiness signing-attempt evidence is partial"); + } + signingAttemptedAtEpochSecond.ifPresent( + attemptedAt -> { + if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { + throw new QuarantinedStateException( + "Readiness signing-attempt time is outside its plan"); + } + }); + if ((state == ProbeState.ABORTED + || state == ProbeState.EXPIRED + || state == ProbeState.CLEANED) + != terminalOutcome.isPresent() + || (state == ProbeState.ABORTED && terminalOutcome.filter("ABORTED"::equals).isEmpty()) + || (state == ProbeState.EXPIRED && terminalOutcome.filter("EXPIRED"::equals).isEmpty()) + || (state == ProbeState.CLEANED + && terminalOutcome + .filter(value -> value.equals("ABORTED") || value.equals("EXPIRED")) + .isEmpty())) { + throw new QuarantinedStateException("Readiness terminal outcome does not match its state"); + } + if ((state == ProbeState.ISSUED || state == ProbeState.VERIFIED) + && compactTokenSha256.isEmpty()) { + throw new QuarantinedStateException("Issued readiness probe has no exact token hash"); + } + if ((state == ProbeState.VERIFIED && verificationReceipt.isEmpty()) + || ((state == ProbeState.PLANNED || state == ProbeState.ISSUED) + && verificationReceipt.isPresent())) { + throw new QuarantinedStateException("Readiness state and verification receipt disagree"); + } + verificationReceipt.ifPresent( + receipt -> { + if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !receipt.verifiedKid().equals(targetKid)) + || receipt.resultEntryVersion() > entryVersion + || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() + || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { + throw new QuarantinedStateException( + "Readiness verification receipt differs from its immutable entry"); + } + }); + if (verificationReceipt.isPresent() + && verificationReceipt.orElseThrow().resultEntryVersion() > entryVersion) { + throw new QuarantinedStateException("Terminal readiness receipt version is invalid"); + } + if (state == ProbeState.CLEANED && terminalOutcome.isEmpty()) { + throw new QuarantinedStateException("Cleaned readiness probe lost its terminal evidence"); + } + } + + private ProbeEntry withPlanDigest(String value) { + return new ProbeEntry( + rotationOperationId, + value, + validatorId, + tokenProfile, + audience, + probeKind, + jti, + targetGeneration, + targetKid, + expectedActive, + registryVersion, + entryVersion, + plannedIssuedAtEpochSecond, + expiresAtEpochSecond, + state, + terminalOutcome, + signingAttemptedAtEpochSecond, + compactTokenSha256, + verificationReceipt); + } + } + + /** Exact authenticated transport and cryptographic verification evidence; contains no token. */ + public record VerifiedProbeObservation( + String compactTokenSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long observedAtEpochSecond) { + public VerifiedProbeObservation { + requireDigest(compactTokenSha256, "verified compact token hash"); + requireKid(verifiedKid); + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification observation is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + /** Immutable digest and identity fields read back from the readiness entry row. */ + public record VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + int podReceiptCount, + String podReceiptClosureSha256) { + public VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256) { + this( + receiptVersion, + sourceEntryVersion, + resultEntryVersion, + observedAtEpochSecond, + receiptSha256, + verifiedKid, + validatorInstanceId, + validatorBindingDigest, + validatorConfigRevision, + validatorPeerUri, + validatorPeerSpkiSha256, + 0, + null); + } + + public VerificationReceipt { + if ((receiptVersion != 1 && receiptVersion != 2) + || sourceEntryVersion <= 0L + || resultEntryVersion != sourceEntryVersion + 1L + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification receipt version is malformed"); + } + requireDigest(receiptSha256, "readiness verification receipt digest"); + if (receiptVersion == 1) { + requireKid(verifiedKid); + if (podReceiptCount != 0 || podReceiptClosureSha256 != null) { + throw new QuarantinedStateException("Legacy receipt cannot carry per-Pod closure fields"); + } + } else { + requireKid(verifiedKid); + if (podReceiptCount <= 0 || podReceiptCount > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Per-Pod receipt closure count is malformed"); + } + requireDigest(podReceiptClosureSha256, "per-Pod receipt closure digest"); + if (!receiptSha256.equals(podReceiptClosureSha256)) { + throw new QuarantinedStateException("Per-Pod closure and verification digests differ"); + } + } + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new QuarantinedStateException("Readiness verification receipt identity is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + public record ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries, + Optional inventorySnapshotDigest) { + public ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries) { + this( + operationId, + binding, + trustFence, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + targetGeneration, + targetKid, + targetPublicKeyFingerprint, + expectedFence, + publicationIntentDigest, + publicationReceiptDigest, + mountedObservationDigest, + applicabilityMatrixJson, + applicabilityMatrixDigest, + validatorInventoryComplete, + maximumCacheAgeSeconds, + plannedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + planVersion, + planDigest, + entries, + Optional.empty()); + } + + public ReadinessProbePlan { + requireOperationId(operationId); + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(expectedFence); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + requireDigest(targetPublicKeyFingerprint, "target public key fingerprint"); + requireDigest(publicationIntentDigest, "publication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(mountedObservationDigest, "mounted observation digest"); + Objects.requireNonNull(applicabilityMatrixJson); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + requireDigest(planDigest, "plan digest"); + Objects.requireNonNull(inventorySnapshotDigest); + inventorySnapshotDigest.ifPresent( + value -> requireDigest(value, "validator inventory snapshot digest")); + entries = List.copyOf(entries); + if (desiredStateVersion <= 1L + || maximumCacheAgeSeconds != MAX_VALIDATOR_CACHE_AGE_SECONDS + || plannedAtEpochSecond <= 0L + || notBeforeEpochSecond < plannedAtEpochSecond + maximumCacheAgeSeconds + || expiresAtEpochSecond <= notBeforeEpochSecond + || expiresAtEpochSecond - notBeforeEpochSecond > PROBE_LIFETIME_SECONDS + || (planVersion != 1 && planVersion != INVENTORY_PLAN_VERSION) + || (planVersion == INVENTORY_PLAN_VERSION && inventorySnapshotDigest.isEmpty()) + || entries.isEmpty() + || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new QuarantinedStateException("Readiness probe plan is malformed"); + } + } + + private static ReadinessProbePlan fromCurrent( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + boolean inventoryComplete, + int maxCacheAge, + long plannedAt, + long notBefore, + long expiresAt, + String planDigest, + List entries, + Optional inventorySnapshotDigest, + int planVersion) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + var publication = current.publication(); + return new ReadinessProbePlan( + request.operationId(), + request.binding(), + request.trustFence(), + request.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + new SignerFence(request.expectedActive(), request.expectedPublishedActive()), + publication.intent().intentDigest(), + publication.receipt().orElseThrow().receiptDigest(), + publication.mountedCorrespondence().orElseThrow().observationDigest(), + matrixJson, + matrixDigest, + inventoryComplete, + maxCacheAge, + plannedAt, + notBefore, + expiresAt, + planVersion, + planDigest, + entries, + inventorySnapshotDigest); + } + } + + /** + * Owner-created, non-secret readiness evidence accepted by the Account promotion owner. Its + * constructor is private: callers cannot turn an applicability matrix or receipt DTO into proof. + */ + public static final class ReadinessPromotionProof { + private final ReadinessProbePlan plan; + private final GenerationResult generationResult; + private final AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication; + private final String inventoryEvidenceReference; + private final String inventoryEvidenceDigest; + private final List verifiedProbes; + private final String readinessEvidenceDigest; + + private ReadinessPromotionProof( + ReadinessProbePlan plan, + GenerationResult generationResult, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest) { + this.plan = Objects.requireNonNull(plan); + this.generationResult = Objects.requireNonNull(generationResult); + this.publication = Objects.requireNonNull(publication); + if (!plan.validatorInventoryComplete()) { + throw new QuarantinedStateException( + "Partial readiness inventory cannot create promotion proof"); + } + if (inventoryEvidenceReference == null + || !inventoryEvidenceReference.matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}")) { + throw new QuarantinedStateException("Protected readiness inventory reference is malformed"); + } + requireDigest(inventoryEvidenceDigest, "protected readiness inventory digest"); + this.inventoryEvidenceReference = inventoryEvidenceReference; + this.inventoryEvidenceDigest = inventoryEvidenceDigest; + List verifiedProbes = + plan.entries().stream().map(VerifiedProbeEvidence::from).toList(); + if (verifiedProbes.isEmpty() + || verifiedProbes.size() > MAX_ENTRIES_PER_OPERATION + || plan.planVersion() != INVENTORY_PLAN_VERSION + || verifiedProbes.stream().anyMatch(probe -> probe.receipt().receiptVersion() != 2) + || !plan.operationId().equals(generationResult.operationId()) + || !plan.operationDigest().equals(generationResult.operationDigest()) + || !plan.generationRequestDigest().equals(generationResult.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generationResult.receiptDigest()) + || plan.desiredStateVersion() != generationResult.desiredStateVersion() + || !plan.targetGeneration().equals(generationResult.targetGeneration()) + || !plan.targetKid().equals(generationResult.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generationResult.publicKeyFingerprint()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Readiness proof differs from exact generation and verified probe evidence"); + } + this.verifiedProbes = List.copyOf(verifiedProbes); + this.readinessEvidenceDigest = + readinessPromotionDigest( + plan, + generationResult, + publication, + inventoryEvidenceReference, + inventoryEvidenceDigest, + this.verifiedProbes); + } + + public ReadinessProbePlan plan() { + return plan; + } + + public GenerationResult generationResult() { + return generationResult; + } + + public AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication() { + return publication; + } + + public String inventoryEvidenceReference() { + return inventoryEvidenceReference; + } + + public String inventoryEvidenceDigest() { + return inventoryEvidenceDigest; + } + + public List verifiedProbes() { + return verifiedProbes; + } + + /** Digest computed by Account over all canonical proof fields except this digest itself. */ + public String readinessEvidenceDigest() { + return readinessEvidenceDigest; + } + } + + /** Ordered immutable row and authenticated receipt identity for one VERIFIED registry entry. */ + public record VerifiedProbeEvidence( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256, + VerificationReceipt receipt) { + public VerifiedProbeEvidence { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "verified probe plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + requireDigest(compactTokenSha256, "verified probe token digest"); + Objects.requireNonNull(receipt); + if (registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || (receipt.receiptVersion() == 1 && !targetKid.equals(receipt.verifiedKid())) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !targetKid.equals(receipt.verifiedKid())) + || receipt.resultEntryVersion() != entryVersion) { + throw new QuarantinedStateException( + "Verified probe evidence does not match its immutable receipt"); + } + } + + private static VerifiedProbeEvidence from(ProbeEntry entry) { + if (entry.state() != ProbeState.VERIFIED) { + throw new QuarantinedStateException( + "Every promotion readiness entry must be owner-recorded VERIFIED"); + } + return new VerifiedProbeEvidence( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + entry.compactTokenSha256().orElseThrow(), + entry.verificationReceipt().orElseThrow()); + } + } + + /** Immutable winner of the only permitted transient delivery for a readiness operation. */ + public record DeliveryClaim( + UUID rotationOperationId, + String planDigest, + String expectedClusterUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String targetGeneration, + String targetKid, + Optional expectedActive, + String readinessBindingDigest, + String readinessConfigRevision, + long readinessBindingValidUntilEpochSecond, + String validatorId, + String validatorInstanceId, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long claimedAtEpochSecond, + long expiresAtEpochSecond, + String claimDigest) { + public DeliveryClaim { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "delivery plan digest"); + requireUuid(expectedClusterUid, "delivery cluster UID"); + requireUuid(expectedNamespaceUid, "delivery namespace UID"); + requireDigest(materializerTrustBindingDigest, "materializer trust digest"); + requireRevision(materializerTrustConfigRevision, "materializer trust revision"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + expectedActive.ifPresent( + active -> { + requireGeneration(active.generation()); + requireKid(active.kid()); + if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) + || targetKid.equals(active.kid())) { + throw new QuarantinedStateException("Delivery active fence is not older than target"); + } + }); + requireDigest(readinessBindingDigest, "readiness trust digest"); + requireRevision(readinessConfigRevision, "readiness trust revision"); + if (readinessBindingValidUntilEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness binding expires before delivery claim"); + } + requireValidatorId(validatorId); + if (!VALIDATOR_ID.equals(validatorId) + || validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + throw new QuarantinedStateException("Readiness delivery identity is malformed"); + } + requireDigest(validatorPeerSpkiSha256, "readiness peer SPKI digest"); + if (claimedAtEpochSecond <= 0L || expiresAtEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness delivery claim window is malformed"); + } + requireDigest(claimDigest, "readiness delivery claim digest"); + } + + private static DeliveryClaim create( + ReadinessProbePlan plan, + TrustFence trust, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + long claimedAt) { + DeliveryClaim unsigned = + new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + trust.expectedClusterIncarnationUid(), + trust.expectedNamespaceUid(), + trust.bindingDigest(), + trust.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + readinessBinding.validUntilEpochSecond(), + readinessBinding.validatorId(), + readinessBinding.validatorInstanceId(), + peer.uri(), + peer.spkiSha256(), + claimedAt, + plan.expiresAtEpochSecond(), + "0".repeat(64)); + return new DeliveryClaim( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.expectedClusterUid(), + unsigned.expectedNamespaceUid(), + unsigned.materializerTrustBindingDigest(), + unsigned.materializerTrustConfigRevision(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.readinessBindingDigest(), + unsigned.readinessConfigRevision(), + unsigned.readinessBindingValidUntilEpochSecond(), + unsigned.validatorId(), + unsigned.validatorInstanceId(), + unsigned.validatorPeerUri(), + unsigned.validatorPeerSpkiSha256(), + unsigned.claimedAtEpochSecond(), + unsigned.expiresAtEpochSecond(), + deliveryClaimDigest(unsigned)); + } + } + + private static String requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || parsed.version() != 4 + || parsed.variant() != 2 + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return value; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static String requireRevision(String value, String label) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireValidatorId(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,62}")) { + throw new QuarantinedStateException("Readiness validator ID is malformed"); + } + return value; + } + + private static String requireProfile(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,127}")) { + throw new QuarantinedStateException("Readiness token profile is malformed"); + } + return value; + } + + private static String requireAudience(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException("Readiness audience is malformed"); + } + return value; + } + + private static String requireGeneration(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,63}")) { + throw new QuarantinedStateException("Readiness signer generation is malformed"); + } + return value; + } + + private static String requireKid(String value) { + if (value == null || !value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new QuarantinedStateException("Readiness signer kid is malformed"); + } + return value; + } + + public static final class MissingPlanException extends IllegalStateException { + public MissingPlanException(String message) { + super(message); + } + } + + public static final class DeliveryAlreadyClaimedException extends IllegalStateException { + public DeliveryAlreadyClaimedException() { + super("Readiness probe delivery was already claimed"); + } + } + + public static final class DeliveryClaimRejectedException extends SecurityException { + public DeliveryClaimRejectedException() { + super("Authenticated readiness delivery caller is not bound to the current plan"); + } + } + + public static final class MissingPublicationEvidenceException extends IllegalStateException { + public MissingPublicationEvidenceException() { + super("Current JWKS publication evidence is incomplete"); + } + } + + public static final class InventoryPlanConflictException extends IllegalStateException { + public InventoryPlanConflictException() { + super("Account validator inventory snapshot does not match the immutable readiness plan"); + } + } + + public static final class StaleOperationException extends IllegalStateException { + public StaleOperationException(String message) { + super(message); + } + } + + public static final class CacheAgeNotElapsedException extends IllegalStateException { + public CacheAgeNotElapsedException() { + super("Validator maximum cache age has not elapsed"); + } + } + + public static final class ProbeExpiredException extends IllegalStateException { + public ProbeExpiredException() { + super("Readiness probe is expired"); + } + } + + public static final class AmbiguousDeliveryException extends IllegalStateException { + public AmbiguousDeliveryException(String message) { + super(message); + } + } + + public static final class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java new file mode 100644 index 0000000000..cc819f0e1d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -0,0 +1,4178 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +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.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned persistence for the interim mounted JWT signer. + * + *

Account chooses and persists the operation, generation, and {@code kid}. The materializer can + * only observe the fixed Secret, then perform one pending-slot generation/CAS or an exact + * PREPARED-only slot promotion and return public-only results. Account remains the sole durable + * commit authority; public prepublication, cache convergence, validator probes, and correspondence + * evidence are separately owned prerequisites and are never inferred by this repository. + */ +@Repository +public class AccountJwtSignerDesiredStateRepository { + public static final String PRIVATE_SECRET_NAME = "jwt-signing-keys"; + public static final String PUBLIC_JWKS_CONFIG_MAP_NAME = "jwt-jwks"; + public static final String REQUEST_DIGEST_VERSION = "account-jwt-signer-generation-operation/v1"; + public static final String OBSERVATION_DIGEST_VERSION = + "account-jwt-signer-secret-observation/v1"; + public static final String GENERATION_REQUEST_DIGEST_VERSION = + "account-jwt-signer-generation-request/v1"; + public static final String RECEIPT_DIGEST_VERSION = "account-jwt-signer-generation-receipt/v1"; + private static final String PROMOTION_DIGEST_VERSION = + "account-jwt-signer-promotion-operation/v1"; + + private static final String STATE_TABLE = "account_jwt_signer_desired_states"; + private static final String OPERATION_TABLE = "account_jwt_signer_generation_operations"; + private static final String OBSERVATION_TABLE = "account_jwt_signer_secret_observations"; + private static final String RESULT_TABLE = "account_jwt_signer_generation_results"; + private static final String PROMOTION_TABLE = "account_jwt_signer_promotion_operations"; + private static final String MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final String ALGORITHM = "RS256"; + private static final String ACTION = "MATERIALIZE_PENDING"; + private static final String PENDING_SLOT = "pending"; + private static final byte[] PENDING_SLOT_CANONICAL_BYTES = + "[\"pending\"]".getBytes(StandardCharsets.UTF_8); + private static final byte[] PROMOTION_SLOTS_CANONICAL_BYTES = + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8); + private static final Pattern ENVIRONMENT_ID = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern SHA256_HEX = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set PUBLIC_JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtSignerDesiredStateRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Enrolls the fixed Account environment only after both protected trust bindings and a live + * fixed-ConfigMap observation have been reconciled by the enrollment owner. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIdentity) { + requireWritableAccountTransaction(); + Objects.requireNonNull(binding, "JWT signer binding is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned JWT signer enrollment is required"); + int inserted = + dsl.execute( + "INSERT INTO " + + STATE_TABLE + + " (environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES (?, ?, ?, ?, 'jwt-signing-keys', 'jwt-jwks', 1, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (environment_id) DO NOTHING", + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + UUID.fromString(enrollmentIdentity.expectedClusterIncarnationUid()), + UUID.fromString(enrollmentIdentity.expectedNamespaceUid()), + enrollmentIdentity.materializerTrustBindingDigest(), + enrollmentIdentity.materializerTrustConfigRevision(), + enrollmentIdentity.apiBindingDigest(), + enrollmentIdentity.apiConfigRevision(), + UUID.fromString(enrollmentIdentity.publicConfigMapUid()), + enrollmentIdentity.publicConfigMapResourceVersion(), + enrollmentIdentity.publicConfigMapSnapshotDigest()); + if (inserted < 0 || inserted > 1) { + throw new StorageUnavailableException("Account JWT signer initialization was ambiguous"); + } + Record row = selectState(binding.environmentId(), true); + if (row == null) { + throw new QuarantinedStateException("Initialized Account JWT signer state did not read back"); + } + DesiredState state = decodeState(row); + requireBinding(state, binding); + if (state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(enrollmentIdentity)) { + throw new BindingMismatchException( + "Account JWT signer enrollment trust or precreated resource identity changed"); + } + if (inserted == 1 && !state.enrollmentIdentity().orElseThrow().equals(enrollmentIdentity)) { + throw new QuarantinedStateException( + "Initial Account JWT signer enrollment receipt did not read back exactly"); + } + if (inserted == 1 + && (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.generationOperationId().isPresent() + || state.preparedOperationId().isPresent())) { + throw new QuarantinedStateException( + "New Account JWT signer state contains inferred or unexpected authority"); + } + return state; + } + + /** + * Returns a pinned enrollment row even while PREPARED so startup reconciliation can inspect it. + * Ordinary desired-state reads continue to quarantine PREPARED signer state. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readEnrollmentState(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + return Optional.empty(); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + return Optional.of(state); + } + + /** Reads an explicitly enrolled state; a missing row never initializes desired state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DesiredState read(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + verifyPreparedIsUnavailable(state); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + } + return state; + } + + /** + * Account's internal operation entrypoint. It receives no caller-selected operation, key + * identity, resource name, fingerprint, or material. Account creates one immutable operation if + * absent, or returns the same operation under the same protected trust snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest ensureCurrentGenerationRequest( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + + if (state.generationOperationId().isEmpty()) { + if (state.durableActive().isPresent()) { + throw new MissingGenerationOperationException( + "Account has no durable rotation request for its committed signer"); + } + return createGenerationRequest(state, trust); + } + + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Returns the same current Account-selected request and exact phase for an authenticated peer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest readCurrentGenerationRequest(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Reads the exact immutable result for Account's current generation operation while locking the + * desired-state, operation, and result rows in their canonical order. A historical result is + * never returned after the Account operation or protected trust fence has moved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult readCurrentGenerationResult(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + GenerationResult result = selectGenerationResult(operationId, true); + if (result == null) { + throw new MissingGenerationObservationException( + "Account JWT generation result is not recorded for the current operation"); + } + verifyGenerationResultMatchesOperation(result, operation, state); + return result; + } + + /** + * Recovery-only read for the exact generation that owns the current PREPARED operation. It is + * intentionally distinct from ordinary serving/generation reads, which continue to fail closed + * while a promotion is unresolved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readPreparedGenerationForRecovery( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state.preparedOperationId().orElseThrow(() -> new NoPreparedPromotionException()); + if (state.generationOperationId().isPresent()) { + throw new QuarantinedStateException( + "Account PREPARED signer state also contains a generation pointer"); + } + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + return new PreparedGenerationEvidence(state, promotion.publicEvidence(), result); + } + + /** + * Atomically records that the authenticated materializer may receive the immutable private-slot + * promotion operation. This marker is deliberately sticky: after it is committed, a lost RPC + * response is an uncertain external mutation and the operation must remain PREPARED for forward + * reconciliation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readAndMarkPreparedPromotionDispatched( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + PreparedGenerationEvidence evidence = readPreparedGenerationForRecovery(expectedBinding, trust); + UUID operationId = evidence.promotion().operationId(); + StoredPromotion promotion = selectPromotion(operationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + if (!promotion.privatePromotionDispatched()) { + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_dispatched_at = CURRENT_TIMESTAMP " + + "WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_dispatched_at IS NULL " + + "AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL", + operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account private promotion dispatch authorization CAS did not apply"); + } + promotion = selectPromotion(operationId, true); + } + if (promotion == null + || !promotion.privatePromotionDispatched() + || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException( + "Account private promotion dispatch authorization did not read back exactly"); + } + return evidence; + } + + /** + * Records one authenticated materializer readback of the exact fixed-Secret slot transition. Only + * public key identities, resource UID/RV, and slot names cross this boundary; private bytes and + * hashes of private bytes are neither accepted nor persisted. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrivatePromotionReceipt recordPrivatePromotionResult( + Binding expectedBinding, TrustFence trust, PrivatePromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); + if (promotion == null) { + throw new StaleGenerationOperationException( + "Private promotion result does not target an Account-owned operation"); + } + requireCurrentTrust(promotion, trust); + if (!promotion.requestDigest().equals(observation.promotionRequestDigest()) + || !promotion.generationOperationId().equals(observation.generationOperationId()) + || !promotion.generationOperationDigest().equals(observation.generationOperationDigest())) { + throw new IdempotencyConflictException( + "Private promotion result does not match the exact Account operation"); + } + if (!promotion.privatePromotionDispatched()) { + throw new PromotionPrerequisitesIncompleteException( + "Private promotion result has no prior durable Account dispatch authorization"); + } + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + requirePrivatePromotionObservation(promotion, observation); + PrivatePromotionReceipt candidate = PrivatePromotionReceipt.from(promotion, observation); + + if ("COMMITTED".equals(promotion.status())) { + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!promotion.binding().equals(expectedBinding) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion)) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(target::equals).isEmpty() + || state.publishedActive().filter(target::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null + || !candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Committed private promotion retry does not match current Account evidence"); + } + return candidate; + } + + if (!"PREPARED".equals(promotion.status()) + || !state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) + || state.generationOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Private promotion result does not target Account's current PREPARED operation"); + } + requirePromotionMatchesState(promotion, state); + if (promotion.privatePromotionReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Private promotion readback changed for the same Account operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_observed_resource_version = ?, " + + "private_promotion_receipt_digest = ? WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account private promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.privatePromotionObservedResourceVersion())) { + throw new QuarantinedStateException( + "Account private promotion receipt did not read back exactly"); + } + return candidate; + } + + /** + * Records Account's exact readback after its fixed public ConfigMap CAS changes only the + * generation marker from PREPUBLISHED to ACTIVE. The public receipt contains no private Secret + * bytes or digest of private material. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ActiveJwksPromotionReceipt recordActiveJwksPromotionResult( + Binding expectedBinding, TrustFence trust, ActiveJwksPromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact Account ConfigMap promotion readback is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state + .preparedOperationId() + .orElseThrow( + () -> + new PromotionPrerequisitesIncompleteException( + "Account has no PREPARED JWT signer promotion")); + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account cannot publish ACTIVE before the exact private-slot readback"); + } + requireActiveJwksObservation(promotion, observation); + ActiveJwksPromotionReceipt candidate = ActiveJwksPromotionReceipt.from(promotion, observation); + if (promotion.activeJwksReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(promotion.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.activeJwksObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Active Account JWT JWKS readback changed for the same promotion operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET active_jwks_observed_resource_version = ?, active_jwks_public_data_digest = ?, " + + "active_jwks_receipt_digest = ? WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.publicDataDigest(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account active JWKS promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(readback.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.activeJwksObservedResourceVersion())) { + throw new QuarantinedStateException("Account active JWKS receipt did not read back exactly"); + } + return candidate; + } + + /** + * Commits only after both exact external-resource receipts are durably read back. The promotion + * row and desired-state active fences transition in one Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedSignerEvidence commitPreparedPromotion( + Binding expectedBinding, + TrustFence trust, + UUID promotionOperationId, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Objects.requireNonNull(readinessProof, "Current Account readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Commit does not target Account's exact PREPARED promotion"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion lacks exact private and public resource receipts"); + } + if (!promotion.privatePromotionDispatched()) { + throw new QuarantinedStateException( + "Account promotion receipts have no durable private dispatch authorization"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed signer generation evidence is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + PromotionPreparation commitPreparation = + new PromotionPreparation( + promotion.generationOperationId(), + result, + state.enrollmentIdentity().orElseThrow(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson()); + requireReadinessProofMatches( + result, commitPreparation, promotion, expectedBinding, trust, readinessProof); + requireUnexpiredCurrentReadinessProof(promotion, result, readinessProof); + + // State is locked first above, matching readiness expiry/cleanup's owner lock order. The + // terminal UPDATE repeats the clock and complete-entry fence atomically; the count query in + // the helper is a validation read, not an entry-row lock. + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'COMMITTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NOT NULL " + + "AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans plan " + + "WHERE plan.rotation_operation_id = ? AND plan.plan_digest = ? " + + "AND plan.validator_inventory_complete = TRUE " + + "AND plan.not_before_epoch_seconds <= " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT " + + "AND plan.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ?) = ? " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ? " + + "AND entry.state = 'VERIFIED' AND entry.verification_receipt_sha256 IS NOT NULL " + + "AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds " + + "AND entry.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) = ?", + promotionOperationId, + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size()); + if (changed != 1) { + throw new VersionConflictException("Account promotion terminal CAS did not apply"); + } + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, durable_active_generation = ?, " + + "durable_active_kid = ?, published_active_generation = ?, published_active_kid = ?, " + + "prepared_operation_id = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND record_version = ? AND prepared_operation_id = ? " + + "AND generation_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + promotionOperationId, + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + if (advanced != 1) { + throw new VersionConflictException("Account committed active-signer CAS did not apply"); + } + StoredPromotion committed = selectPromotion(promotionOperationId, true); + Record committedStateRow = selectState(expectedBinding.environmentId(), true); + if (committed == null || committedStateRow == null || !"COMMITTED".equals(committed.status())) { + throw new QuarantinedStateException("Account committed promotion did not read back"); + } + DesiredState committedState = decodeState(committedStateRow); + requireCommittedStateMatches(committed, committedState); + return new CommittedSignerEvidence( + committed.publicEvidence(), + result, + committedState, + PrivatePromotionReceipt.fromStored(committed), + ActiveJwksPromotionReceipt.fromStored(committed)); + } + + /** + * Aborts only before either Kubernetes mutation was recorded. Once either external write may have + * happened, the operation remains PREPARED for exact forward recovery rather than guessing + * rollback state. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AbortedPromotion abortPreparedBeforeMutation( + Binding expectedBinding, TrustFence trust, UUID promotionOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Abort does not target the exact PREPARED operation"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest() != null + || promotion.activeJwksReceiptDigest() != null) { + throw new PromotionPrerequisitesIncompleteException( + "A dispatched promotion must remain PREPARED for forward reconciliation"); + } + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'ABORTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL " + + "AND private_promotion_dispatched_at IS NULL", + promotionOperationId); + if (changed != 1) + throw new VersionConflictException("Account promotion abort CAS did not apply"); + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, prepared_operation_id = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND record_version = ? " + + "AND prepared_operation_id = ? AND generation_operation_id IS NULL", + expectedBinding.environmentId(), + state.recordVersion(), + promotionOperationId); + if (advanced != 1) + throw new VersionConflictException("Account signer abort state CAS did not apply"); + StoredPromotion aborted = selectPromotion(promotionOperationId, true); + DesiredState abortedState = decodeState(selectState(expectedBinding.environmentId(), true)); + if (aborted == null + || !"ABORTED".equals(aborted.status()) + || abortedState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Account aborted promotion did not read back exactly"); + } + return new AbortedPromotion( + promotionOperationId, + abortedState.recordVersion(), + abortedState.durableActive(), + abortedState.publishedActive()); + } + + /** Reads only the exact Account-committed generation and both durable resource receipts. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Account signer lifecycle is unresolved and cannot serve a committed signer"); + } + if (state.durableActive().isEmpty() || !state.durableActive().equals(state.publishedActive())) { + throw new QuarantinedStateException( + "Account durable and published active signer fences disagree"); + } + ActiveSigner active = state.durableActive().orElseThrow(); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation pending = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (pending == null) { + throw new QuarantinedStateException("Current Account generation operation is missing"); + } + verifyOperationMatchesState(pending, state); + requireCurrentTrust(pending, trust); + } + StoredPromotion promotion = selectCommittedPromotion(state, active); + if (promotion == null) { + throw new QuarantinedStateException( + "Account active signer has no exact committed promotion receipt"); + } + requireCurrentTrust(promotion, trust); + requireCommittedActiveStillCurrent(promotion, state); + if (!promotion.apiBindingDigest().equals(currentApiBindingDigest) + || !promotion.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException( + "Committed signer uses an obsolete Account JWKS API binding"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), false); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed Account generation result is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer is missing exact resource receipts"); + } + return Optional.of( + new CommittedSignerEvidence( + promotion.publicEvidence(), + result, + state, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** + * Reads the original committed signer after ordinary rotation. This authenticates retained + * lifecycle provenance only; the caller must separately verify that the original public JWK is + * still accepted by the current protected JWKS source. No current-active equality is imposed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readOriginalCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision, + UUID promotionOperationId, + UUID generationOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding); + Objects.requireNonNull(trust); + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState current = decodeState(stateRow); + requireBinding(current, expectedBinding); + requireEnrollmentTrust(current, trust); + EnrollmentIdentity enrollment = current.enrollmentIdentity().orElseThrow(); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, false); + if (promotion == null) return Optional.empty(); + requireCurrentTrust(promotion, trust); + if (!"COMMITTED".equals(promotion.status()) + || !expectedBinding.equals(promotion.binding()) + || !generationOperationId.equals(promotion.generationOperationId()) + || !currentApiBindingDigest.equals(promotion.apiBindingDigest()) + || !currentApiConfigRevision.equals(promotion.apiConfigRevision())) { + throw new QuarantinedStateException("Original committed signer identity differs"); + } + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, false); + GenerationResult result = selectGenerationResult(generationOperationId, false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Original committed signer generation is absent"); + } + requireCurrentTrust(generation, trust); + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Original committed signer resource receipts are absent"); + } + return Optional.of( + new OriginalCommittedSignerEvidence( + promotion.publicEvidence(), + result, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** Immutable historical owner readback, not an active-key or authenticated-actor grant. */ + public record OriginalCommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public OriginalCommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId())) { + throw new QuarantinedStateException("Original committed signer linkage is inconsistent"); + } + } + } + + /** Persists the pinned materializer's read-only observation of the fixed pre-created Secret. */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest recordSecretObservation( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "JWT generation operation digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + if (!current.operation().operationDigest().equals(operationDigest)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation does not match the Account operation digest"); + } + SecretObservation candidate = + SecretObservation.from(current.operation(), secretUid, observedResourceVersion); + SecretObservation existing = selectSecretObservation(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation changed for the same Account operation"); + } + return readGenerationRequest(current.operation(), current.state(), true); + } + + insertSecretObservation(candidate); + SecretObservation readback = selectSecretObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer Secret observation did not read back exactly"); + } + return toGenerationRequest(current.operation(), current.state(), readback, null); + } + + /** + * Persists one public-only key-generation result. Account validates the canonical RSA JWK and + * derives the RFC 7638 fingerprint; private members, tokens, and caller fingerprints are not + * accepted. Exact retries return the immutable receipt; changed/stale retries fail closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult recordGenerationResult( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, generationRequestDigest, "JWT generation request digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + PublicJwk publicJwk = parsePublicJwk(publicJwkJson); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + StoredGenerationOperation operation = current.operation(); + SecretObservation observation = selectSecretObservation(operationId, true); + if (observation == null) { + throw new MissingGenerationObservationException( + "JWT signer generation cannot precede exact Secret observation"); + } + if (!observation.secretUid().equals(secretUid) + || !observation.observedResourceVersion().equals(expectedPriorResourceVersion) + || !observation.generationRequestDigest().equals(generationRequestDigest)) { + throw new StaleGenerationOperationException( + "JWT signer generation result does not match the observed Secret fence"); + } + if (!publicJwk.kid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer public JWK does not match the Account-selected key identity"); + } + + GenerationResult candidate = + GenerationResult.from( + operation, + current.state().recordVersion(), + observation, + observedResourceVersion, + publicJwk); + GenerationResult existing = selectGenerationResult(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer generation result changed for the same Account operation"); + } + return existing; + } + + insertGenerationResult(candidate); + GenerationResult readback = selectGenerationResult(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer generation result did not read back exactly"); + } + return readback; + } + + /** + * Persists PREPARED only for exact owner-readback generation, prepublication, and readiness + * evidence supplied by the lifecycle coordinator. The database independently locks and checks the + * generation/publication/readiness rows; caller booleans and signer/JWKS agreement alone cannot + * enter PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedPromotion prepareCurrentGeneration( + Binding expectedBinding, + TrustFence trust, + PromotionPreparation preparation, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(preparation, "Owner-readback promotion preparation is required"); + Objects.requireNonNull(readinessProof, "Account-verified readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + if (!enrollment.sameStablePins(preparation.enrollmentIdentity()) + || !enrollment.apiBindingDigest().equals(preparation.apiBindingDigest()) + || !enrollment.apiConfigRevision().equals(preparation.apiConfigRevision()) + || !enrollment.publicConfigMapUid().equals(preparation.publicConfigMapUid())) { + throw new BindingMismatchException( + "JWT signer promotion trust does not match the independently pinned enrollment"); + } + if (state.preparedOperationId().isPresent()) { + StoredPromotion replay = selectPromotion(state.preparedOperationId().orElseThrow(), true); + if (replay == null || !"PREPARED".equals(replay.status())) { + throw new QuarantinedStateException("Account PREPARED promotion is missing"); + } + requirePromotionMatchesState(replay, state); + requireCurrentTrust(replay, trust); + StoredGenerationOperation replayGeneration = + selectGenerationOperation(replay.generationOperationId(), true); + GenerationResult replayResult = selectGenerationResult(replay.generationOperationId(), true); + if (replayGeneration == null || replayResult == null) { + throw new QuarantinedStateException("Prepared promotion source generation is missing"); + } + verifyPreparedGenerationMatches(replay, replayGeneration, replayResult); + if (!replay.matchesPreparation(preparation, replayGeneration, replayResult, enrollment)) { + throw new IdempotencyConflictException( + "JWT signer promotion retry changed its immutable evidence"); + } + requireReadinessProofMatches( + replayResult, preparation, replay, expectedBinding, trust, readinessProof); + return new PreparedPromotion(replay.operationId(), replay.requestDigest(), "PREPARED"); + } + UUID generationOperationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no current generation operation to promote")); + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, true); + GenerationResult result = selectGenerationResult(generationOperationId, true); + if (generation == null || result == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account generation operation has no exact persisted result"); + } + verifyOperationMatchesState(generation, state); + requireCurrentTrust(generation, trust); + verifyGenerationResultMatchesOperation(result, generation, state); + if (!result.equals(preparation.generationResult()) + || !preparation.generationOperationId().equals(generationOperationId)) { + throw new StaleGenerationOperationException( + "Promotion preparation does not match the exact current generation result"); + } + requireReadinessProofMatches(result, preparation, null, expectedBinding, trust, readinessProof); + requireCurrentPublicationForPreparation(result, preparation); + requireCurrentReadinessForPreparation(result, preparation); + + StoredPromotion candidate = + StoredPromotion.create(preparation, state, generation, result, trust, expectedBinding); + StoredPromotion existing = selectPromotion(candidate.operationId(), true); + if (existing != null) { + requirePromotionMatchesState(existing, state); + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer promotion request changed for the same operation"); + } + return new PreparedPromotion(existing.operationId(), existing.requestDigest(), "PREPARED"); + } + insertPromotion(candidate); + int advanced = advanceToPrepared(state, candidate.operationId()); + if (advanced != 1) { + throw new VersionConflictException("Account desired state changed while entering PREPARED"); + } + StoredPromotion readback = selectPromotion(candidate.operationId(), true); + Record stateReadbackRow = selectState(expectedBinding.environmentId(), true); + if (readback == null || stateReadbackRow == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Account PREPARED promotion did not read back exactly"); + } + DesiredState stateReadback = decodeState(stateReadbackRow); + requirePromotionMatchesState(readback, stateReadback); + return new PreparedPromotion(readback.operationId(), readback.requestDigest(), "PREPARED"); + } + + private static void requireReadinessProofMatches( + GenerationResult result, + PromotionPreparation preparation, + StoredPromotion preparedReplay, + Binding expectedBinding, + TrustFence trust, + ReadinessPromotionProof proof) { + var plan = proof.plan(); + var publication = proof.publication(); + if (!proof.generationResult().equals(result) + || !preparation.generationResult().equals(result) + || !plan.operationId().equals(result.operationId()) + || !plan.binding().equals(expectedBinding) + || !plan.trustFence().equals(trust) + || !plan.planDigest().equals(preparation.readinessPlanDigest()) + || !proof.readinessEvidenceDigest().equals(preparation.readinessEvidenceDigest()) + || !plan.operationDigest().equals(result.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !publication.intent().intentDigest().equals(preparation.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(preparation.prepublicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(preparation.mountedObservationDigest()) + || !publication.intent().configMapUid().equals(preparation.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(preparation.expectedPublicResourceVersion()) + || !publication.intent().apiBindingDigest().equals(preparation.apiBindingDigest()) + || !publication.intent().apiConfigRevision().equals(preparation.apiConfigRevision()) + || !publication.intent().jwksJson().equals(preparation.expectedPublicJwksJson())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof does not match the exact generation and publication"); + } + if (preparedReplay != null + && (!preparedReplay.readinessPlanDigest().equals(plan.planDigest()) + || !preparedReplay.readinessEvidenceDigest().equals(proof.readinessEvidenceDigest()))) { + throw new IdempotencyConflictException( + "Readiness recovery proof changed for the exact PREPARED promotion"); + } + if (!plan.validatorInventoryComplete() + || proof.inventoryEvidenceReference() == null + || !proof.inventoryEvidenceReference().matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}") + || proof.inventoryEvidenceDigest() == null + || !proof.inventoryEvidenceDigest().matches("[0-9a-f]{64}") + || proof.verifiedProbes().isEmpty() + || !proof.readinessEvidenceDigest().matches("[0-9a-f]{64}") + || !publication.intent().operationId().equals(result.operationId()) + || !publication.receipt().operationId().equals(result.operationId()) + || !publication.mountedCorrespondence().operationId().equals(result.operationId()) + || !publication.intent().intentDigest().equals(plan.publicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(plan.publicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(plan.mountedObservationDigest())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof lacks exact publication or protected inventory evidence"); + } + } + + private GenerationRequest createGenerationRequest(DesiredState state, TrustFence trust) { + if (state.recordVersion() == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer state version is exhausted"); + } + long previousGeneration = + Math.max( + state.durableActive().map(value -> parseGeneration(value.generation())).orElse(0L), + state.publishedActive().map(value -> parseGeneration(value.generation())).orElse(0L)); + if (previousGeneration == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer generation is exhausted"); + } + long targetGeneration = previousGeneration + 1; + UUID operationId = UUID.randomUUID(); + String targetKid = "jwt-" + targetGeneration + "-" + operationId.toString().substring(0, 12); + StoredGenerationOperation operation = + StoredGenerationOperation.create(state, trust, operationId, targetGeneration, targetKid); + insertGenerationOperation(operation); + int changed = advanceToGenerationRequest(state, operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account JWT signer state changed during request creation"); + } + Record readbackStateRow = selectState(state.binding().environmentId(), true); + Record readbackOperationRow = selectGenerationOperationRow(operationId, true); + if (readbackStateRow == null || readbackOperationRow == null) { + throw new QuarantinedStateException("Account JWT generation request did not read back"); + } + DesiredState readbackState = decodeState(readbackStateRow); + StoredGenerationOperation readbackOperation = decodeGenerationOperation(readbackOperationRow); + requireBinding(readbackState, state.binding()); + verifyOperationMatchesState(readbackOperation, readbackState); + if (!readbackOperation.equals(operation)) { + throw new QuarantinedStateException("Account JWT generation request changed on readback"); + } + return readGenerationRequest(readbackOperation, readbackState, true); + } + + private GenerationRequest readGenerationRequest( + StoredGenerationOperation operation, DesiredState state, boolean lockEvidence) { + GenerationResult result = selectGenerationResult(operation.operationId(), lockEvidence); + if (result != null) { + verifyGenerationResultMatchesOperation(result, operation, state); + return toGenerationRequest(operation, state, null, result); + } + SecretObservation observation = selectSecretObservation(operation.operationId(), lockEvidence); + if (observation != null) { + verifySecretObservationMatchesOperation(observation, operation, state); + } + return toGenerationRequest(operation, state, observation, null); + } + + private static void verifySecretObservationMatchesOperation( + SecretObservation observation, StoredGenerationOperation operation, DesiredState state) { + if (!observation.operationId().equals(operation.operationId()) + || !observation.binding().equals(operation.binding()) + || !observation.operationDigest().equals(operation.operationDigest()) + || observation.expectedRecordVersion() != operation.expectedRecordVersion() + || !observation.trustFence().equals(operation.trustFence()) + || state.recordVersion() != operation.expectedRecordVersion() + 1) { + throw new QuarantinedStateException( + "JWT signer Secret observation is not bound to its operation"); + } + } + + private static void verifyGenerationResultMatchesOperation( + GenerationResult result, StoredGenerationOperation operation, DesiredState state) { + if (!result.operationId().equals(operation.operationId()) + || !result.binding().equals(operation.binding()) + || !result.operationDigest().equals(operation.operationDigest()) + || !result.trustFence().equals(operation.trustFence()) + || result.desiredStateVersion() != state.recordVersion() + || !result.targetGeneration().equals(operation.targetGeneration()) + || !result.targetKid().equals(operation.targetKid()) + || !result.targetAlgorithm().equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer generation result is not bound to its operation"); + } + } + + private GenerationRequest toGenerationRequest( + StoredGenerationOperation operation, + DesiredState state, + SecretObservation observation, + GenerationResult result) { + GenerationPhase phase = + result != null + ? GenerationPhase.GENERATION_RECORDED + : observation != null + ? GenerationPhase.GENERATE_PENDING + : GenerationPhase.OBSERVE_PRIVATE_SECRET; + return new GenerationRequest( + phase, + operation.operationId(), + operation.operationDigest(), + result != null + ? result.generationRequestDigest() + : observation == null ? "" : observation.generationRequestDigest(), + state.recordVersion(), + operation.binding(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + ACTION, + List.of(PENDING_SLOT), + operation.expectedPreviousActive(), + operation.expectedPublishedActive(), + result != null ? result.secretUid() : observation == null ? "" : observation.secretUid(), + result != null + ? result.expectedPriorResourceVersion() + : observation == null ? "" : observation.observedResourceVersion(), + result == null ? "" : result.receiptDigest(), + result == null ? "" : result.publicKeyFingerprint(), + result == null ? "" : result.publicJwkJson(), + result == null ? "" : result.observedResourceVersion()); + } + + private LockedCurrent lockCurrentOperation( + Binding expectedBinding, TrustFence trust, UUID operationId) { + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + if (!state.generationOperationId().equals(Optional.of(operationId))) { + throw new StaleGenerationOperationException( + "JWT signer request does not target Account's current generation operation"); + } + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return new LockedCurrent(state, operation); + } + + private void requireCurrentTrust(StoredGenerationOperation operation, TrustFence current) { + if (!operation.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed for the generation operation"); + } + } + + private static void requireEnrollmentTrust(DesiredState state, TrustFence trust) { + EnrollmentIdentity enrolled = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity")); + if (!enrolled.expectedClusterIncarnationUid().equals(trust.expectedClusterIncarnationUid()) + || !enrolled.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !enrolled.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !enrolled.materializerTrustConfigRevision().equals(trust.configRevision())) { + throw new BindingMismatchException( + "JWT materializer trust no longer matches Account's pinned enrollment"); + } + } + + private void verifyOperationMatchesState( + StoredGenerationOperation operation, DesiredState state) { + if (!state.generationOperationId().equals(Optional.of(operation.operationId())) + || !operation.binding().equals(state.binding()) + || operation.expectedRecordVersion() == Long.MAX_VALUE + || state.recordVersion() != operation.expectedRecordVersion() + 1 + || !operation.expectedPreviousActive().equals(state.durableActive()) + || !operation.expectedPublishedActive().equals(state.publishedActive()) + || !REQUEST_DIGEST_VERSION.equals(operation.digestVersion()) + || !generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException( + "Account JWT signer generation request does not match current desired state"); + } + } + + private Record selectState(String environmentId, boolean lock) { + return dsl.fetchOne( + "SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest FROM " + + STATE_TABLE + + " WHERE environment_id = ?" + + (lock ? " FOR UPDATE" : ""), + environmentId); + } + + private StoredPromotion selectPromotion(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT p.operation_id, p.environment_id, p.cluster_id, p.kubernetes_namespace, p.custody_mode, " + + "p.request_digest_version, p.request_digest, p.expected_record_version, " + + "p.expected_previous_generation, p.expected_previous_kid, p.target_generation, p.target_kid, " + + "p.target_algorithm, p.target_public_key_fingerprint, " + + "p.expected_private_secret_resource_version, p.expected_public_jwks_resource_version, " + + "p.expected_public_active_generation, p.expected_public_active_kid, p.operation_action, " + + "p.allowed_private_slots_canonical_bytes, p.status, p.generation_operation_id, " + + "p.expected_cluster_incarnation_uid, p.expected_namespace_uid, " + + "p.materializer_trust_binding_digest, p.materializer_trust_config_revision, " + + "p.api_binding_digest, p.api_config_revision, p.expected_private_secret_uid, " + + "p.expected_public_config_map_uid, p.prepublication_intent_digest, " + + "p.prepublication_receipt_digest, p.mounted_observation_digest, p.readiness_plan_digest, " + + "p.readiness_evidence_digest, p.expected_public_jwks_json, " + + "p.expected_active_generation_marker_json, " + + "(p.private_promotion_dispatched_at IS NOT NULL) AS private_promotion_dispatched, " + + "p.private_promotion_observed_resource_version, " + + "p.private_promotion_receipt_digest, p.active_jwks_observed_resource_version, " + + "p.active_jwks_public_data_digest, p.active_jwks_receipt_digest, " + + "generation.operation_digest AS generation_operation_digest, " + + "generation_result.receipt_digest AS generation_receipt_digest " + + "FROM " + + PROMOTION_TABLE + + " AS p " + + "JOIN " + + OPERATION_TABLE + + " AS generation " + + "ON generation.operation_id = p.generation_operation_id " + + "JOIN " + + RESULT_TABLE + + " AS generation_result " + + "ON generation_result.operation_id = p.generation_operation_id " + + "WHERE p.operation_id = ?" + + (lock ? " FOR UPDATE OF p, generation, generation_result" : ""), + operationId); + return row == null ? null : decodePromotion(row); + } + + private StoredPromotion selectCommittedPromotion(DesiredState state, ActiveSigner active) { + Result rows = + dsl.fetch( + "SELECT operation_id FROM " + + PROMOTION_TABLE + + " WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND status = 'COMMITTED' AND target_generation = ? " + + "AND target_kid = ? ORDER BY created_at DESC LIMIT 2", + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + parseGeneration(active.generation()), + active.kid()); + if (rows.size() != 1) { + throw new QuarantinedStateException( + "Account active signer does not resolve to exactly one committed promotion"); + } + UUID operationId = rows.get(0).get("operation_id", UUID.class); + return selectPromotion(operationId, false); + } + + private static void requireCommittedStateMatches(StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() != promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer does not match its exact operation and active fences"); + } + } + + private static void requireCommittedActiveStillCurrent( + StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2) { + throw new QuarantinedStateException( + "Committed Account promotion is not the current active signer"); + } + } + + private static void requireActiveJwksObservation( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || observation.priorResourceVersion().equals(observation.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(observation.jwksJson()) + || !promotion.expectedActiveMarkerJson().equals(observation.activeMarkerJson())) { + throw new QuarantinedStateException( + "Account ConfigMap CAS did not read back the exact authorized ACTIVE projection"); + } + requireActiveMarkerMatchesPromotion(promotion, observation.activeMarkerJson()); + } + + private static void requireActiveMarkerMatchesPromotion( + StoredPromotion promotion, String marker) { + try { + JsonNode root = STRICT_JSON.readTree(marker); + if (root == null + || !root.isObject() + || root.size() != 11 + || !root.path("schemaVersion").isIntegralNumber() + || root.path("schemaVersion").intValue() != 1 + || !"ACTIVE".equals(requiredText(root, "phase", 16)) + || !promotion + .generationOperationId() + .toString() + .equals(requiredText(root, "operationId", 36)) + || !promotion + .generationOperationDigest() + .equals(requiredText(root, "operationDigest", 64)) + || !promotion + .generationReceiptDigest() + .equals(requiredText(root, "generationReceiptDigest", 64)) + || !markerBindingMatches(promotion, root.get("binding")) + || !markerFenceMatches( + promotion, root.get("expectedDurableActive"), promotion.expectedPreviousActive()) + || !markerFenceMatches( + promotion, root.get("expectedPublishedActive"), promotion.expectedPublishedActive()) + || !markerPublicMapMatches(root.get("publicConfigMap")) + || !markerPromotionMatches(promotion, root.get("promotion"))) { + throw new IllegalArgumentException("Active marker mismatch"); + } + JsonNode active = root.get("active"); + if (active == null + || !active.isObject() + || active.size() != 4 + || !promotion.targetGeneration().equals(requiredText(active, "generation", 19)) + || !promotion.targetKid().equals(requiredText(active, "kid", 64)) + || !ALGORITHM.equals(requiredText(active, "algorithm", 16)) + || !promotion + .targetPublicKeyFingerprint() + .equals(requiredText(active, "publicKeyFingerprint", 64))) { + throw new IllegalArgumentException("Active signer mismatch"); + } + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account ACTIVE generation marker is malformed", ex); + } + } + + private static boolean markerBindingMatches(StoredPromotion promotion, JsonNode binding) { + return binding != null + && binding.isObject() + && binding.size() == 9 + && promotion.binding().environmentId().equals(requiredText(binding, "environmentId", 64)) + && promotion.binding().clusterId().equals(requiredText(binding, "clusterId", 128)) + && promotion.binding().namespace().equals(requiredText(binding, "namespace", 64)) + && promotion + .trustFence() + .expectedClusterIncarnationUid() + .equals(requiredText(binding, "expectedClusterIncarnationUid", 36)) + && promotion + .trustFence() + .expectedNamespaceUid() + .equals(requiredText(binding, "expectedNamespaceUid", 36)) + && promotion + .trustFence() + .bindingDigest() + .equals(requiredText(binding, "trustBindingDigest", 64)) + && promotion + .trustFence() + .configRevision() + .equals(requiredText(binding, "trustConfigRevision", 128)) + && promotion.apiBindingDigest().equals(requiredText(binding, "apiBindingDigest", 64)) + && promotion.apiConfigRevision().equals(requiredText(binding, "apiConfigRevision", 128)); + } + + private static boolean markerFenceMatches( + StoredPromotion promotion, JsonNode fence, Optional expected) { + return fence != null && parseMarkerActive(fence).equals(expected); + } + + private static Optional parseMarkerActive(JsonNode fence) { + if (fence == null || !fence.isObject()) { + throw new IllegalArgumentException("Active marker fence is malformed"); + } + if (fence.size() == 1 + && fence.path("present").isBoolean() + && !fence.path("present").booleanValue()) { + return Optional.empty(); + } + if (fence.size() == 3 + && fence.path("present").isBoolean() + && fence.path("present").booleanValue()) { + return Optional.of( + new ActiveSigner(requiredText(fence, "generation", 19), requiredText(fence, "kid", 64))); + } + throw new IllegalArgumentException("Active marker fence is malformed"); + } + + private static boolean markerPublicMapMatches(JsonNode publicMap) { + return publicMap != null + && publicMap.isObject() + && publicMap.size() == 1 + && PUBLIC_JWKS_CONFIG_MAP_NAME.equals(requiredText(publicMap, "name", 64)); + } + + private static boolean markerPromotionMatches(StoredPromotion promotion, JsonNode proof) { + return proof != null + && proof.isObject() + && proof.size() == 7 + && promotion.operationId().toString().equals(requiredText(proof, "operationId", 36)) + && promotion.requestDigest().equals(requiredText(proof, "requestDigest", 64)) + && promotion + .prepublicationIntentDigest() + .equals(requiredText(proof, "prepublicationIntentDigest", 64)) + && promotion + .prepublicationReceiptDigest() + .equals(requiredText(proof, "prepublicationReceiptDigest", 64)) + && promotion + .mountedObservationDigest() + .equals(requiredText(proof, "mountedObservationDigest", 64)) + && promotion.readinessPlanDigest().equals(requiredText(proof, "readinessPlanDigest", 64)) + && promotion + .readinessEvidenceDigest() + .equals(requiredText(proof, "readinessEvidenceDigest", 64)); + } + + private static String activeMarkerJson(StoredPromotion promotion) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "ACTIVE"); + marker.put("operationId", promotion.generationOperationId().toString()); + marker.put("operationDigest", promotion.generationOperationDigest()); + marker.put("generationReceiptDigest", promotion.generationReceiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", promotion.binding().environmentId()); + binding.put("clusterId", promotion.binding().clusterId()); + binding.put("namespace", promotion.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", promotion.trustFence().bindingDigest()); + binding.put("trustConfigRevision", promotion.trustFence().configRevision()); + binding.put("apiBindingDigest", promotion.apiBindingDigest()); + binding.put("apiConfigRevision", promotion.apiConfigRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", PUBLIC_JWKS_CONFIG_MAP_NAME)); + marker.put("expectedDurableActive", activeMarker(promotion.expectedPreviousActive())); + marker.put("expectedPublishedActive", activeMarker(promotion.expectedPublishedActive())); + marker.put( + "active", + Map.of( + "generation", promotion.targetGeneration(), + "kid", promotion.targetKid(), + "algorithm", promotion.targetAlgorithm(), + "publicKeyFingerprint", promotion.targetPublicKeyFingerprint())); + marker.put( + "promotion", + Map.of( + "operationId", promotion.operationId().toString(), + "requestDigest", promotion.requestDigest(), + "prepublicationIntentDigest", promotion.prepublicationIntentDigest(), + "prepublicationReceiptDigest", promotion.prepublicationReceiptDigest(), + "mountedObservationDigest", promotion.mountedObservationDigest(), + "readinessPlanDigest", promotion.readinessPlanDigest(), + "readinessEvidenceDigest", promotion.readinessEvidenceDigest())); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException("Account ACTIVE JWT marker could not be canonicalized"); + } + } + + private static Map activeMarker(Optional active) { + Map marker = new LinkedHashMap<>(); + marker.put("present", active.isPresent()); + active.ifPresent( + signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); + return marker; + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new IllegalArgumentException("Account JWT signer JSON field is malformed"); + } + return value.textValue(); + } + + private static void requirePromotionMatchesState(StoredPromotion promotion, DesiredState state) { + if (!promotion.binding().equals(state.binding()) + || !state.preparedOperationId().equals(Optional.of(promotion.operationId())) + || state.generationOperationId().isPresent() + || state.recordVersion() != promotion.expectedRecordVersion() + 1 + || !promotion.expectedPreviousActive().equals(state.durableActive()) + || !promotion.expectedPublishedActive().equals(state.publishedActive()) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion))) { + throw new QuarantinedStateException( + "Account PREPARED promotion does not match its exact desired-state fence"); + } + } + + private static void requireCurrentTrust(StoredPromotion promotion, TrustFence current) { + if (!promotion.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed during promotion"); + } + } + + private static void verifyPreparedGenerationMatches( + StoredPromotion promotion, StoredGenerationOperation operation, GenerationResult result) { + if (!promotion.generationOperationId().equals(operation.operationId()) + || !promotion.binding().equals(operation.binding()) + || !promotion.operationDigestForGeneration().equals(operation.operationDigest()) + || !promotion.expectedPreviousActive().equals(operation.expectedPreviousActive()) + || !promotion.expectedPublishedActive().equals(operation.expectedPublishedActive()) + || !promotion.targetGeneration().equals(operation.targetGeneration()) + || !promotion.targetKid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm()) + || !promotion.trustFence().equals(operation.trustFence()) + || !promotion.generationOperationId().equals(result.operationId()) + || !promotion.generationReceiptDigest().equals(result.receiptDigest()) + || !promotion.secretUid().equals(result.secretUid()) + || !promotion.expectedPrivateResourceVersion().equals(result.observedResourceVersion()) + || !promotion.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new QuarantinedStateException( + "Prepared promotion is not bound to the exact source generation result"); + } + } + + private static void requirePrivatePromotionObservation( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Optional expectedPrevious = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); + PublicKeyIdentity expectedCurrent = + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + List expectedSlots = + expectedPrevious.isPresent() ? List.of("current", "previous") : List.of("current"); + if (!observation.secretUid().equals(promotion.secretUid()) + || !observation + .expectedPriorResourceVersion() + .equals(promotion.expectedPrivateResourceVersion()) + || observation.expectedPriorResourceVersion().equals(observation.observedResourceVersion()) + || !expectedCurrent.equals(observation.current()) + || !expectedPrevious.equals(observation.previous()) + || !expectedSlots.equals(observation.resultingSlots())) { + throw new QuarantinedStateException( + "Materializer did not read back the exact authorized private slot transition"); + } + } + + private static String publicFingerprintForKid(String jwksJson, String kid) { + try { + JsonNode root = STRICT_JSON.readTree(jwksJson); + JsonNode keys = root == null ? null : root.get("keys"); + if (keys == null || !keys.isArray()) { + throw new IllegalArgumentException("JWKS keys are malformed"); + } + String found = null; + for (JsonNode key : keys) { + if (key != null && key.isObject() && kid.equals(requiredText(key, "kid", 64))) { + if (found != null) { + throw new IllegalArgumentException("JWKS contains a duplicate kid"); + } + found = + digest( + Map.of( + "e", + requiredText(key, "e", 16), + "kty", + "RSA", + "n", + requiredText(key, "n", 4096))); + } + } + if (found == null) { + throw new IllegalArgumentException("Expected prior public key is missing from JWKS"); + } + return found; + } catch (Exception ex) { + throw new QuarantinedStateException("Expected prior public key identity is unavailable", ex); + } + } + + private StoredPromotion decodePromotion(Record row) { + try { + byte[] slots = row.get("allowed_private_slots_canonical_bytes", byte[].class); + if (!Arrays.equals(PROMOTION_SLOTS_CANONICAL_BYTES, slots) + || !"PROMOTE_PENDING".equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException( + "Account promotion action or fixed Secret slots are malformed"); + } + StoredPromotion promotion = + new StoredPromotion( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + Math.toIntExact( + positive( + row.get("request_digest_version", Short.class).longValue(), + "promotion digest version")), + row.get("request_digest", String.class), + positive( + row.get("expected_record_version", Long.class), "expected signer state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "previous signer"), + activeOptional( + row.get("expected_public_active_generation", Long.class), + row.get("expected_public_active_kid", String.class), + "published previous signer"), + canonicalGeneration( + row.get("target_generation", Long.class), "promotion target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("target_public_key_fingerprint", String.class), + row.get("expected_private_secret_resource_version", String.class), + row.get("expected_public_jwks_resource_version", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class)), + row.get("generation_operation_id", UUID.class), + row.get("generation_operation_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("expected_private_secret_uid", UUID.class).toString(), + row.get("expected_public_config_map_uid", UUID.class).toString(), + row.get("prepublication_intent_digest", String.class), + row.get("prepublication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("readiness_plan_digest", String.class), + row.get("readiness_evidence_digest", String.class), + row.get("expected_public_jwks_json", String.class), + row.get("expected_active_generation_marker_json", String.class), + row.get("status", String.class), + Boolean.TRUE.equals(row.get("private_promotion_dispatched", Boolean.class)), + row.get("private_promotion_observed_resource_version", String.class), + row.get("private_promotion_receipt_digest", String.class), + row.get("active_jwks_observed_resource_version", String.class), + row.get("active_jwks_public_data_digest", String.class), + row.get("active_jwks_receipt_digest", String.class)); + if (promotion.requestDigestVersion() != 1 + || !promotionRequestDigest(promotion).equals(promotion.requestDigest())) { + throw new QuarantinedStateException("Account promotion operation digest is invalid"); + } + return promotion; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account promotion operation is malformed", ex); + } + } + + private static String promotionRequestDigest(StoredPromotion promotion) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", PROMOTION_DIGEST_VERSION); + preimage.put("operationId", promotion.operationId().toString()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("environmentId", promotion.binding().environmentId()); + preimage.put("clusterId", promotion.binding().clusterId()); + preimage.put("namespace", promotion.binding().namespace()); + preimage.put("custodyMode", promotion.binding().mode().value()); + preimage.put("expectedRecordVersion", Long.toString(promotion.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(promotion.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(promotion.expectedPublishedActive())); + preimage.put("targetGeneration", promotion.targetGeneration()); + preimage.put("targetKid", promotion.targetKid()); + preimage.put("targetAlgorithm", ALGORITHM); + preimage.put("targetPublicKeyFingerprint", promotion.targetPublicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", promotion.secretUid()); + preimage.put( + "expectedPrivateSecretResourceVersion", promotion.expectedPrivateResourceVersion()); + preimage.put("expectedPublicConfigMapUid", promotion.publicConfigMapUid()); + preimage.put("expectedPublicJwksResourceVersion", promotion.expectedPublicResourceVersion()); + preimage.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", promotion.trustFence().bindingDigest()); + preimage.put("materializerTrustConfigRevision", promotion.trustFence().configRevision()); + preimage.put("apiBindingDigest", promotion.apiBindingDigest()); + preimage.put("apiConfigRevision", promotion.apiConfigRevision()); + preimage.put("prepublicationIntentDigest", promotion.prepublicationIntentDigest()); + preimage.put("prepublicationReceiptDigest", promotion.prepublicationReceiptDigest()); + preimage.put("mountedObservationDigest", promotion.mountedObservationDigest()); + preimage.put("readinessPlanDigest", promotion.readinessPlanDigest()); + preimage.put("readinessEvidenceDigest", promotion.readinessEvidenceDigest()); + preimage.put("publicJwksSha256", sha256(promotion.expectedPublicJwksJson())); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + return digest(preimage); + } + + private Record selectGenerationOperationRow(UUID operationId, boolean lock) { + return dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + } + + private StoredGenerationOperation selectGenerationOperation(UUID operationId, boolean lock) { + Record row = selectGenerationOperationRow(operationId, lock); + return row == null ? null : decodeGenerationOperation(row); + } + + private SecretObservation selectSecretObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, expected_record_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "private_secret_name, secret_uid, observed_resource_version, observation_digest, " + + "generation_request_digest FROM " + + OBSERVATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeSecretObservation(row); + } + + private GenerationResult selectGenerationResult(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest " + + "FROM " + + RESULT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeGenerationResult(row); + } + + private void insertGenerationOperation(StoredGenerationOperation operation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'MATERIALIZE_PENDING', ?) ", + operation.operationId(), + operation.binding().environmentId(), + operation.binding().clusterId(), + operation.binding().namespace(), + operation.binding().mode().value(), + operation.operationDigest(), + operation.expectedRecordVersion(), + generationValue(operation.expectedPreviousActive()), + kidValue(operation.expectedPreviousActive()), + generationValue(operation.expectedPublishedActive()), + kidValue(operation.expectedPublishedActive()), + parseGeneration(operation.targetGeneration()), + operation.targetKid(), + operation.targetAlgorithm(), + UUID.fromString(operation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(operation.trustFence().expectedNamespaceUid()), + operation.trustFence().bindingDigest(), + operation.trustFence().configRevision(), + PENDING_SLOT_CANONICAL_BYTES); + if (inserted != 1) { + throw new StorageUnavailableException( + "Account JWT generation operation insert was ambiguous"); + } + } + + private void requireCurrentPublicationForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record evidence = + dsl.fetchOne( + "SELECT intent.operation_id, intent.intent_digest, intent.environment_id, intent.cluster_id, " + + "intent.kubernetes_namespace, intent.custody_mode, intent.operation_digest, " + + "intent.generation_request_digest, intent.generation_receipt_digest, " + + "intent.desired_state_version, intent.expected_cluster_incarnation_uid, " + + "intent.expected_namespace_uid, intent.trust_binding_digest, " + + "intent.trust_config_revision, intent.api_binding_digest, intent.api_config_revision, " + + "intent.config_map_name, intent.config_map_uid, intent.jwks_json, " + + "receipt.receipt_digest, receipt.observed_resource_version, " + + "mount.observation_digest FROM account_jwt_jwks_prepublication_intents AS intent " + + "JOIN account_jwt_jwks_publication_receipts AS receipt " + + "ON receipt.operation_id = intent.operation_id " + + "AND receipt.intent_digest = intent.intent_digest " + + "JOIN account_jwt_jwks_mount_observations AS mount " + + "ON mount.operation_id = intent.operation_id " + + "WHERE intent.operation_id = ? FOR UPDATE OF intent, receipt, mount", + result.operationId()); + if (evidence == null + || !preparation + .prepublicationIntentDigest() + .equals(evidence.get("intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(evidence.get("receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(evidence.get("observation_digest", String.class)) + || !preparation + .publicConfigMapUid() + .equals(evidence.get("config_map_uid", UUID.class).toString()) + || !preparation + .expectedPublicResourceVersion() + .equals(evidence.get("observed_resource_version", String.class)) + || !preparation.apiBindingDigest().equals(evidence.get("api_binding_digest", String.class)) + || !preparation + .apiConfigRevision() + .equals(evidence.get("api_config_revision", String.class)) + || !preparation.expectedPublicJwksJson().equals(evidence.get("jwks_json", String.class)) + || !result.operationId().equals(evidence.get("operation_id", UUID.class)) + || !result.operationDigest().equals(evidence.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(evidence.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(evidence.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != evidence.get("desired_state_version", Long.class)) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account JWKS prepublication, API readback, or mount receipt is unavailable"); + } + } + + private void requireCurrentReadinessForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record plan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "validator_inventory_complete, expires_at_epoch_seconds " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + preparation.readinessPlanDigest()); + if (plan == null + || !Boolean.TRUE.equals(plan.get("validator_inventory_complete", Boolean.class)) + || plan.get("expires_at_epoch_seconds", Long.class) == null + || plan.get("expires_at_epoch_seconds", Long.class) == null + || !result.operationDigest().equals(plan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(plan.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(plan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != plan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(plan.get("target_generation", Long.class))) + || !result.targetKid().equals(plan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(plan.get("target_public_key_fingerprint", String.class)) + || !preparation + .prepublicationIntentDigest() + .equals(plan.get("publication_intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(plan.get("publication_receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(plan.get("mounted_observation_digest", String.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Complete current Account JWT readiness proof is unavailable"); + } + Record entries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds) AS verified " + + "FROM account_jwt_readiness_probe_entries WHERE rotation_operation_id = ? " + + "AND plan_digest = ? AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans " + + "WHERE rotation_operation_id = ? AND plan_digest = ? " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT)", + result.operationId(), + preparation.readinessPlanDigest(), + result.operationId(), + preparation.readinessPlanDigest()); + if (entries == null + || entries.get("total", Long.class) == null + || entries.get("total", Long.class) <= 0 + || !entries.get("total", Long.class).equals(entries.get("verified", Long.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact current Account JWT validator probe must be VERIFIED"); + } + } + + /** + * Rechecks the owner-created typed proof at the durable COMMITTED boundary. A proof read before + * this transaction is insufficient: the plan and every VERIFIED entry must still be inside their + * recorded validity window when Account commits the promotion. + */ + private void requireUnexpiredCurrentReadinessProof( + StoredPromotion promotion, GenerationResult result, ReadinessPromotionProof proof) { + var expectedPlan = proof.plan(); + Record currentPlan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "applicability_matrix_digest, validator_inventory_complete, " + + "maximum_cache_age_seconds, not_before_epoch_seconds, expires_at_epoch_seconds, " + + "floor(extract(epoch FROM clock_timestamp()))::bigint AS checked_epoch " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + promotion.readinessPlanDigest()); + if (currentPlan == null + || !Boolean.TRUE.equals(currentPlan.get("validator_inventory_complete", Boolean.class)) + || !promotion.readinessPlanDigest().equals(currentPlan.get("plan_digest", String.class)) + || !result.operationDigest().equals(currentPlan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(currentPlan.get("generation_request_digest", String.class)) + || !result + .receiptDigest() + .equals(currentPlan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != currentPlan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(currentPlan.get("target_generation", Long.class))) + || !result.targetKid().equals(currentPlan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(currentPlan.get("target_public_key_fingerprint", String.class)) + || !promotion + .prepublicationIntentDigest() + .equals(currentPlan.get("publication_intent_digest", String.class)) + || !promotion + .prepublicationReceiptDigest() + .equals(currentPlan.get("publication_receipt_digest", String.class)) + || !promotion + .mountedObservationDigest() + .equals(currentPlan.get("mounted_observation_digest", String.class)) + || !expectedPlan + .applicabilityMatrixDigest() + .equals(currentPlan.get("applicability_matrix_digest", String.class)) + || expectedPlan.maximumCacheAgeSeconds() + != currentPlan.get("maximum_cache_age_seconds", Short.class) + || expectedPlan.notBeforeEpochSecond() + != currentPlan.get("not_before_epoch_seconds", Long.class) + || expectedPlan.expiresAtEpochSecond() + != currentPlan.get("expires_at_epoch_seconds", Long.class) + || currentPlan.get("checked_epoch", Long.class) == null + || currentPlan.get("checked_epoch", Long.class) < expectedPlan.notBeforeEpochSecond() + || currentPlan.get("checked_epoch", Long.class) >= expectedPlan.expiresAtEpochSecond()) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account readiness proof is missing, changed, or expired at commit"); + } + + Record currentEntries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM clock_timestamp()))::bigint) " + + "AS verified FROM account_jwt_readiness_probe_entries " + + "WHERE rotation_operation_id = ? AND plan_digest = ?", + result.operationId(), + promotion.readinessPlanDigest()); + Long total = currentEntries == null ? null : currentEntries.get("total", Long.class); + Long verified = currentEntries == null ? null : currentEntries.get("verified", Long.class); + if (total == null + || verified == null + || total <= 0L + || total != proof.verifiedProbes().size() + || !total.equals(verified)) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact Account validator proof must remain VERIFIED and unexpired at commit"); + } + } + + private void insertPromotion(StoredPromotion promotion) { + int inserted = + dsl.execute( + "INSERT INTO " + + PROMOTION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "request_digest_version, request_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, target_generation, target_kid, " + + "target_algorithm, target_public_key_fingerprint, " + + "expected_private_secret_resource_version, expected_public_jwks_resource_version, " + + "expected_public_active_generation, expected_public_active_kid, operation_action, " + + "allowed_private_slots_canonical_bytes, status, generation_operation_id, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "materializer_trust_binding_digest, materializer_trust_config_revision, " + + "api_binding_digest, api_config_revision, expected_private_secret_uid, " + + "expected_public_config_map_uid, prepublication_intent_digest, " + + "prepublication_receipt_digest, mounted_observation_digest, readiness_plan_digest, " + + "readiness_evidence_digest, expected_public_jwks_json, " + + "expected_active_generation_marker_json) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RS256', ?, ?, ?, ?, ?, " + + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + promotion.operationId(), + promotion.binding().environmentId(), + promotion.binding().clusterId(), + promotion.binding().namespace(), + promotion.binding().mode().value(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + generationValue(promotion.expectedPreviousActive()), + kidValue(promotion.expectedPreviousActive()), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint(), + promotion.expectedPrivateResourceVersion(), + promotion.expectedPublicResourceVersion(), + generationValue(promotion.expectedPublishedActive()), + kidValue(promotion.expectedPublishedActive()), + PROMOTION_SLOTS_CANONICAL_BYTES, + promotion.generationOperationId(), + UUID.fromString(promotion.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(promotion.trustFence().expectedNamespaceUid()), + promotion.trustFence().bindingDigest(), + promotion.trustFence().configRevision(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + UUID.fromString(promotion.secretUid()), + UUID.fromString(promotion.publicConfigMapUid()), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + if (inserted != 1) { + throw new StorageUnavailableException("Account promotion operation insert was ambiguous"); + } + } + + private int advanceToPrepared(DesiredState state, UUID promotionOperationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = NULL, " + + "prepared_operation_id = ?, updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? " + + "AND cluster_id = ? AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND record_version = ? AND generation_operation_id = ? AND prepared_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + promotionOperationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + state.generationOperationId().orElseThrow(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private int advanceToGenerationRequest(DesiredState state, UUID operationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND cluster_id = ? " + + "AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND private_secret_name = 'jwt-signing-keys' " + + "AND public_jwks_config_map_name = 'jwt-jwks' AND record_version = ? " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ? " + + "AND generation_operation_id IS NULL AND prepared_operation_id IS NULL", + operationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private void insertSecretObservation(SecretObservation observation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OBSERVATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, observed_resource_version, " + + "observation_digest_version, observation_digest, generation_request_digest) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, 1, ?, ?)", + observation.operationId(), + observation.binding().environmentId(), + observation.binding().clusterId(), + observation.binding().namespace(), + observation.binding().mode().value(), + observation.operationDigest(), + observation.expectedRecordVersion(), + UUID.fromString(observation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(observation.trustFence().expectedNamespaceUid()), + observation.trustFence().bindingDigest(), + observation.trustFence().configRevision(), + UUID.fromString(observation.secretUid()), + observation.observedResourceVersion(), + observation.observationDigest(), + observation.generationRequestDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT Secret observation insert was ambiguous"); + } + } + + private void insertGenerationResult(GenerationResult result) { + int inserted = + dsl.execute( + "INSERT INTO " + + RESULT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, ?, ?, ?, 'RS256', ?, ?, ?)", + result.operationId(), + result.binding().environmentId(), + result.binding().clusterId(), + result.binding().namespace(), + result.binding().mode().value(), + result.operationDigest(), + result.generationRequestDigest(), + result.desiredStateVersion(), + UUID.fromString(result.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(result.trustFence().expectedNamespaceUid()), + result.trustFence().bindingDigest(), + result.trustFence().configRevision(), + UUID.fromString(result.secretUid()), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + parseGeneration(result.targetGeneration()), + result.targetKid(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + result.receiptDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT generation result insert was ambiguous"); + } + } + + private DesiredState decodeState(Record row) { + try { + if (!PRIVATE_SECRET_NAME.equals(row.get("private_secret_name", String.class)) + || !PUBLIC_JWKS_CONFIG_MAP_NAME.equals( + row.get("public_jwks_config_map_name", String.class))) { + throw new QuarantinedStateException("Account JWT signer resource binding is malformed"); + } + return new DesiredState( + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + positive(row.get("record_version", Long.class), "Account JWT signer record version"), + activeOptional( + row.get("durable_active_generation", Long.class), + row.get("durable_active_kid", String.class), + "durable active signer"), + activeOptional( + row.get("published_active_generation", Long.class), + row.get("published_active_kid", String.class), + "published active signer"), + Optional.ofNullable(row.get("generation_operation_id", UUID.class)), + Optional.ofNullable(row.get("prepared_operation_id", UUID.class)), + enrollmentIdentity(row)); + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account JWT signer desired state is malformed", ex); + } + } + + private static Optional enrollmentIdentity(Record row) { + UUID clusterUid = row.get("enrollment_cluster_incarnation_uid", UUID.class); + UUID namespaceUid = row.get("enrollment_namespace_uid", UUID.class); + String materializerDigest = row.get("enrollment_materializer_binding_digest", String.class); + String materializerRevision = row.get("enrollment_materializer_config_revision", String.class); + String apiDigest = row.get("enrollment_api_binding_digest", String.class); + String apiRevision = row.get("enrollment_api_config_revision", String.class); + UUID configMapUid = row.get("enrollment_public_config_map_uid", UUID.class); + String resourceVersion = row.get("enrollment_public_config_map_resource_version", String.class); + String snapshotDigest = row.get("enrollment_public_config_map_snapshot_digest", String.class); + boolean allAbsent = + clusterUid == null + && namespaceUid == null + && materializerDigest == null + && materializerRevision == null + && apiDigest == null + && apiRevision == null + && configMapUid == null + && resourceVersion == null + && snapshotDigest == null; + if (allAbsent) { + return Optional.empty(); + } + if (clusterUid == null + || namespaceUid == null + || materializerDigest == null + || materializerRevision == null + || apiDigest == null + || apiRevision == null + || configMapUid == null + || resourceVersion == null + || snapshotDigest == null) { + throw new QuarantinedStateException("Account JWT signer enrollment pins are partial"); + } + return Optional.of( + new EnrollmentIdentity( + clusterUid.toString(), + namespaceUid.toString(), + materializerDigest, + materializerRevision, + apiDigest, + apiRevision, + configMapUid.toString(), + resourceVersion, + snapshotDigest)); + } + + private StoredGenerationOperation decodeGenerationOperation(Record row) { + try { + String slotBytes = + new String( + row.get("allowed_private_slots_canonical_bytes", byte[].class), + StandardCharsets.UTF_8); + if (!"[\"pending\"]".equals(slotBytes)) { + throw new QuarantinedStateException("JWT signer operation private slots are malformed"); + } + Integer digestVersion = row.get("operation_digest_version", Integer.class); + StoredGenerationOperation operation = + new StoredGenerationOperation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + digestVersion != null && digestVersion == 1 ? REQUEST_DIGEST_VERSION : "unsupported", + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "expected active signer"), + activeOptional( + row.get("expected_published_generation", Long.class), + row.get("expected_published_kid", String.class), + "expected published signer"), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class))); + if (!ACTION.equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException("JWT signer operation action is unsupported"); + } + if (!generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException("JWT signer operation digest is invalid"); + } + return operation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException( + "Account JWT signer generation operation is malformed", ex); + } + } + + private SecretObservation decodeSecretObservation(Record row) { + try { + SecretObservation observation = + new SecretObservation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("observed_resource_version", String.class), + row.get("observation_digest", String.class), + row.get("generation_request_digest", String.class)); + if (!observationDigest( + observation.operationDigest(), + observation.trustFence(), + observation.secretUid(), + observation.observedResourceVersion()) + .equals(observation.observationDigest()) + || !generationRequestDigest(observation).equals(observation.generationRequestDigest())) { + throw new QuarantinedStateException("JWT signer Secret observation digest is invalid"); + } + return observation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT Secret observation is malformed", ex); + } + } + + private GenerationResult decodeGenerationResult(Record row) { + try { + GenerationResult result = + new GenerationResult( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("expected_prior_resource_version", String.class), + row.get("observed_resource_version", String.class), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("public_key_fingerprint", String.class), + row.get("public_jwk_json", String.class), + row.get("receipt_digest", String.class)); + PublicJwk jwk = parsePublicJwk(result.publicJwkJson()); + if (!jwk.kid().equals(result.targetKid()) + || !jwk.fingerprint().equals(result.publicKeyFingerprint()) + || !generationReceiptDigest(result).equals(result.receiptDigest())) { + throw new QuarantinedStateException("JWT signer generation receipt digest is invalid"); + } + return result; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT generation result is malformed", ex); + } + } + + private static void verifyPreparedIsUnavailable(DesiredState state) { + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Existing PREPARED signer state requires unavailable lifecycle evidence"); + } + } + + private static void requireBinding(DesiredState state, Binding expected) { + if (!state.binding().equals(expected)) { + throw new BindingMismatchException( + "Account JWT signer environment, cluster, namespace, or custody binding changed"); + } + } + + private static String generationOperationDigest(StoredGenerationOperation operation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", REQUEST_DIGEST_VERSION); + preimage.put("environmentId", operation.binding().environmentId()); + preimage.put("clusterId", operation.binding().clusterId()); + preimage.put("namespace", operation.binding().namespace()); + preimage.put("custodyMode", operation.binding().mode().value()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("operationId", operation.operationId().toString()); + preimage.put("expectedRecordVersion", Long.toString(operation.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(operation.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(operation.expectedPublishedActive())); + preimage.put("targetGeneration", operation.targetGeneration()); + preimage.put("targetKid", operation.targetKid()); + preimage.put("targetAlgorithm", operation.targetAlgorithm()); + preimage.put("operationAction", ACTION); + preimage.put("allowedPrivateSlots", List.of(PENDING_SLOT)); + preimage.put( + "expectedClusterIncarnationUid", operation.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", operation.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", operation.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", operation.trustFence().configRevision()); + return digest(preimage); + } + + private static String observationDigest( + String operationDigest, TrustFence trust, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", OBSERVATION_DIGEST_VERSION, + "operationDigest", operationDigest, + "privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME), + "expectedClusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "expectedNamespaceUid", trust.expectedNamespaceUid(), + "trustBindingDigest", trust.bindingDigest(), + "trustConfigRevision", trust.configRevision(), + "secretUid", secretUid, + "observedResourceVersion", resourceVersion)); + } + + private static String generationRequestDigest(SecretObservation observation) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", observation.operationDigest(), + "observationDigest", observation.observationDigest(), + "secretUid", observation.secretUid(), + "expectedPriorResourceVersion", observation.observedResourceVersion(), + "target", "pending")); + } + + private static String generationReceiptDigest(GenerationResult result) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", RECEIPT_DIGEST_VERSION); + preimage.put("operationId", result.operationId().toString()); + preimage.put("operationDigest", result.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("desiredStateVersion", Long.toString(result.desiredStateVersion())); + preimage.put("environmentId", result.binding().environmentId()); + preimage.put("clusterId", result.binding().clusterId()); + preimage.put("namespace", result.binding().namespace()); + preimage.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", result.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", result.trustFence().configRevision()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", result.secretUid()); + preimage.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", result.observedResourceVersion()); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetAlgorithm", result.targetAlgorithm()); + preimage.put("publicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("publicJwk", result.publicJwkJson()); + return digest(preimage); + } + + private static String digest(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("Account JWT signer evidence digest is unavailable", ex); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable for JWT promotion evidence", ex); + } + } + + private static Object activeDigestValue(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner value = active.orElseThrow(); + return Map.of("present", true, "generation", value.generation(), "kid", value.kid()); + } + + private static PublicJwk parsePublicJwk(String json) { + if (json == null || json.isEmpty() || json.getBytes(StandardCharsets.UTF_8).length > 8_192) { + throw new IllegalArgumentException("JWT signer public JWK is missing or too large"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject() || node.size() != PUBLIC_JWK_FIELDS.size()) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported shape"); + } + for (Map.Entry property : node.properties()) { + if (!PUBLIC_JWK_FIELDS.contains(property.getKey())) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported field"); + } + } + String canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonicalJson.equals(json)) { + throw new IllegalArgumentException("JWT signer public JWK must be canonical RFC 8785 JSON"); + } + String kty = requiredText(node, "kty", 8); + String use = requiredText(node, "use", 8); + String algorithm = requiredText(node, "alg", 8); + String kid = requiredText(node, "kid", 64); + String modulus = requiredText(node, "n", 4_096); + String exponent = requiredText(node, "e", 16); + JsonNode keyOps = node.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException("JWT signer public JWK does not meet RS256 policy"); + } + byte[] modulusBytes = decodeCanonicalBase64Url(modulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(exponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw new IllegalArgumentException("JWT signer RSA public numbers are malformed"); + } + BigInteger modulusInteger = new BigInteger(1, modulusBytes); + BigInteger exponentInteger = new BigInteger(1, exponentBytes); + if (modulusInteger.bitLength() < 3_072 + || modulusInteger.bitLength() > 16_384 + || !modulusInteger.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentInteger)) { + throw new IllegalArgumentException("JWT signer RSA public key is outside policy"); + } + } finally { + java.util.Arrays.fill(modulusBytes, (byte) 0); + java.util.Arrays.fill(exponentBytes, (byte) 0); + } + String fingerprint = + digest( + Map.of( + "e", exponent, + "kty", "RSA", + "n", modulus)); + return new PublicJwk(kid, canonicalJson, fingerprint); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer public JWK is malformed", ex); + } + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("JWT signer RSA public number is malformed", ex); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean matches = canonical.length == encoded.length(); + for (int index = 0; matches && index < canonical.length; index++) { + matches = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + java.util.Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !matches) { + java.util.Arrays.fill(decoded, (byte) 0); + throw new IllegalArgumentException("JWT signer RSA public number is not canonical"); + } + return decoded; + } + + private static ActiveSigner active(Long generation, String kid, String field) { + if (generation == null && kid == null) { + return null; + } + if (generation == null || kid == null) { + throw new QuarantinedStateException(field + " has an incomplete generation/kid pair"); + } + return new ActiveSigner(Long.toString(positive(generation, field + " generation")), kid); + } + + private static Optional activeOptional(Long generation, String kid, String field) { + return Optional.ofNullable(active(generation, kid, field)); + } + + private static Long generationValue(Optional active) { + return active.map(value -> parseGeneration(value.generation())).orElse(null); + } + + private static String kidValue(Optional active) { + return active.map(ActiveSigner::kid).orElse(null); + } + + private static String canonicalGeneration(Long value, String field) { + return Long.toString(positive(value, field)); + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0) { + throw new QuarantinedStateException(field + " must be positive"); + } + return value; + } + + private static long parseGeneration(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Signer generation must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Signer generation is outside its supported range", ex); + } + } + + private static void requireOperationId(UUID operationId) { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + if (operationId.version() != 4) { + throw new IllegalArgumentException("Account JWT signer operation ID must be UUIDv4"); + } + } + + private static void requireUuid(String value, String field) { + if (value == null) { + throw new IllegalArgumentException("JWT signer " + field + " is missing"); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireMatch(Pattern pattern, String value, String field) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction is required for JWT signer state"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Writable Account transaction is required for JWT signer state"); + } + } + + public enum CustodyMode { + INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK(MODE); + + private final String value; + + CustodyMode(String value) { + this.value = value; + } + + public String value() { + return value; + } + + private static CustodyMode fromValue(String value) { + for (CustodyMode candidate : values()) { + if (candidate.value.equals(value)) { + return candidate; + } + } + throw new QuarantinedStateException("JWT signer custody mode is unsupported"); + } + } + + public enum GenerationPhase { + OBSERVE_PRIVATE_SECRET, + GENERATE_PENDING, + GENERATION_RECORDED + } + + public record Binding( + String environmentId, String clusterId, String namespace, CustodyMode mode) { + public Binding { + requireMatch(ENVIRONMENT_ID, environmentId, "environment ID"); + requireMatch(CLUSTER_ID, clusterId, "cluster ID"); + requireMatch(ENVIRONMENT_ID, namespace, "Kubernetes namespace"); + Objects.requireNonNull(mode, "JWT signer custody mode is required"); + } + } + + /** Independently protected trust identity captured by every immutable operation and receipt. */ + public record TrustFence( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String bindingDigest, + String configRevision) { + public TrustFence { + requireUuid(expectedClusterIncarnationUid, "expected cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "expected namespace UID"); + requireMatch(SHA256_HEX, bindingDigest, "materializer trust binding digest"); + requireMatch(CLUSTER_ID, configRevision, "materializer trust configuration revision"); + } + } + + /** + * Immutable independently protected trust and first ConfigMap observation used for enrollment. + */ + public record EnrollmentIdentity( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) { + public EnrollmentIdentity { + requireUuid(expectedClusterIncarnationUid, "enrollment cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "enrollment namespace UID"); + requireMatch(SHA256_HEX, materializerTrustBindingDigest, "materializer trust digest"); + requireMatch(CLUSTER_ID, materializerTrustConfigRevision, "materializer trust revision"); + requireMatch(SHA256_HEX, apiBindingDigest, "public JWKS API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public JWKS API configuration revision"); + requireUuid(publicConfigMapUid, "pre-created public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, publicConfigMapResourceVersion, "initial ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, publicConfigMapSnapshotDigest, "initial ConfigMap snapshot digest"); + } + + /** Stable pin equality deliberately excludes the historical first ConfigMap RV/data digest. */ + public boolean sameStablePins(EnrollmentIdentity other) { + Objects.requireNonNull(other, "Enrollment identity is required"); + return expectedClusterIncarnationUid.equals(other.expectedClusterIncarnationUid) + && expectedNamespaceUid.equals(other.expectedNamespaceUid) + && materializerTrustBindingDigest.equals(other.materializerTrustBindingDigest) + && materializerTrustConfigRevision.equals(other.materializerTrustConfigRevision) + && apiBindingDigest.equals(other.apiBindingDigest) + && apiConfigRevision.equals(other.apiConfigRevision) + && publicConfigMapUid.equals(other.publicConfigMapUid); + } + } + + public record ActiveSigner(String generation, String kid) { + public ActiveSigner { + parseGeneration(generation); + requireMatch(KID, kid, "active signer kid"); + } + } + + public record DesiredState( + Binding binding, + long recordVersion, + Optional durableActive, + Optional publishedActive, + Optional generationOperationId, + Optional preparedOperationId, + Optional enrollmentIdentity) { + public DesiredState { + Objects.requireNonNull(binding, "JWT signer binding is required"); + if (recordVersion <= 0) { + throw new IllegalArgumentException("JWT signer record version must be positive"); + } + durableActive = Objects.requireNonNull(durableActive, "Durable active signer is required"); + publishedActive = + Objects.requireNonNull(publishedActive, "Published active signer is required"); + generationOperationId = + Objects.requireNonNull(generationOperationId, "Generation operation state is required"); + preparedOperationId = + Objects.requireNonNull(preparedOperationId, "Prepared operation state is required"); + enrollmentIdentity = + Objects.requireNonNull(enrollmentIdentity, "Enrollment identity state is required"); + if (generationOperationId.isPresent() && preparedOperationId.isPresent()) { + throw new IllegalArgumentException("Generation and PREPARED pointers cannot coexist"); + } + } + } + + public record GenerationRequest( + GenerationPhase phase, + UUID operationId, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + Binding binding, + TrustFence trustFence, + String privateSecretName, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String operationAction, + List allowedPrivateSlots, + Optional expectedActive, + Optional expectedPublishedActive, + String secretUid, + String expectedSecretResourceVersion, + String generationReceiptDigest, + String publicKeyFingerprint, + String publicJwkJson, + String observedSecretResourceVersion) { + public GenerationRequest { + Objects.requireNonNull(phase, "Generation phase is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } else if (generationRequestDigest != null && !generationRequestDigest.isEmpty()) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation request state version is invalid"); + } + Objects.requireNonNull(binding, "Generation request binding is required"); + Objects.requireNonNull(trustFence, "Generation request trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName) + || !ALGORITHM.equals(targetAlgorithm) + || !ACTION.equals(operationAction) + || !List.of(PENDING_SLOT).equals(allowedPrivateSlots)) { + throw new QuarantinedStateException("JWT generation request fixed operation is malformed"); + } + allowedPrivateSlots = List.copyOf(allowedPrivateSlots); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + expectedActive = Objects.requireNonNull(expectedActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + secretUid = secretUid == null ? "" : secretUid; + expectedSecretResourceVersion = + expectedSecretResourceVersion == null ? "" : expectedSecretResourceVersion; + generationReceiptDigest = generationReceiptDigest == null ? "" : generationReceiptDigest; + publicKeyFingerprint = publicKeyFingerprint == null ? "" : publicKeyFingerprint; + publicJwkJson = publicJwkJson == null ? "" : publicJwkJson; + observedSecretResourceVersion = + observedSecretResourceVersion == null ? "" : observedSecretResourceVersion; + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedSecretResourceVersion, "observed Secret resourceVersion"); + } + if (phase == GenerationPhase.GENERATION_RECORDED) { + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + parsePublicJwk(publicJwkJson); + requireMatch( + RESOURCE_VERSION, observedSecretResourceVersion, "result Secret resourceVersion"); + } else if (!generationReceiptDigest.isEmpty() + || !publicKeyFingerprint.isEmpty() + || !publicJwkJson.isEmpty() + || !observedSecretResourceVersion.isEmpty()) { + throw new QuarantinedStateException( + "Incomplete JWT generation request contains result evidence"); + } + } + } + + public record GenerationResult( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String publicKeyFingerprint, + String publicJwkJson, + String receiptDigest) { + public GenerationResult { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation result binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation result state version is invalid"); + } + Objects.requireNonNull(trustFence, "Generation result trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("JWT generation result must name the fixed Secret"); + } + requireUuid(secretUid, "generation result Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 JWT signer results are supported"); + } + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + requireMatch(SHA256_HEX, receiptDigest, "generation receipt digest"); + PublicJwk jwk = parsePublicJwk(publicJwkJson); + if (!jwk.kid().equals(targetKid) || !jwk.fingerprint().equals(publicKeyFingerprint)) { + throw new QuarantinedStateException( + "JWT generation result public key does not match receipt"); + } + } + + private static GenerationResult from( + StoredGenerationOperation operation, + long desiredStateVersion, + SecretObservation observation, + String observedResourceVersion, + PublicJwk jwk) { + GenerationResult candidate = + new GenerationResult( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + observation.generationRequestDigest(), + desiredStateVersion, + operation.trustFence(), + PRIVATE_SECRET_NAME, + observation.secretUid(), + observation.observedResourceVersion(), + observedResourceVersion, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + jwk.fingerprint(), + jwk.canonicalJson(), + "0".repeat(64)); + return new GenerationResult( + candidate.operationId(), + candidate.binding(), + candidate.operationDigest(), + candidate.generationRequestDigest(), + candidate.desiredStateVersion(), + candidate.trustFence(), + candidate.privateSecretName(), + candidate.secretUid(), + candidate.expectedPriorResourceVersion(), + candidate.observedResourceVersion(), + candidate.targetGeneration(), + candidate.targetKid(), + candidate.targetAlgorithm(), + candidate.publicKeyFingerprint(), + candidate.publicJwkJson(), + generationReceiptDigest(candidate)); + } + } + + private record StoredGenerationOperation( + UUID operationId, + Binding binding, + String digestVersion, + String operationDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + TrustFence trustFence) { + private StoredGenerationOperation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation operation binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Generation operation state version is invalid"); + } + expectedPreviousActive = + Objects.requireNonNull(expectedPreviousActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 generation operations are supported"); + } + Objects.requireNonNull(trustFence, "Generation operation trust is required"); + } + + private static StoredGenerationOperation create( + DesiredState state, + TrustFence trust, + UUID operationId, + long targetGeneration, + String targetKid) { + StoredGenerationOperation unsigned = + new StoredGenerationOperation( + operationId, + state.binding(), + REQUEST_DIGEST_VERSION, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + Long.toString(targetGeneration), + targetKid, + ALGORITHM, + trust); + return new StoredGenerationOperation( + unsigned.operationId(), + unsigned.binding(), + unsigned.digestVersion(), + generationOperationDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.trustFence()); + } + } + + private record SecretObservation( + UUID operationId, + Binding binding, + String operationDigest, + long expectedRecordVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String observedResourceVersion, + String observationDigest, + String generationRequestDigest) { + private SecretObservation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Secret observation binding is required"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Secret observation state version is invalid"); + } + requireMatch(SHA256_HEX, operationDigest, "operation digest"); + Objects.requireNonNull(trustFence, "Secret observation trust is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("Secret observation must name the fixed Secret"); + } + requireUuid(secretUid, "observed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + requireMatch(SHA256_HEX, observationDigest, "Secret observation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + + private static SecretObservation from( + StoredGenerationOperation operation, String secretUid, String resourceVersion) { + String observationDigest = + AccountJwtSignerDesiredStateRepository.observationDigest( + operation.operationDigest(), operation.trustFence(), secretUid, resourceVersion); + String generationRequestDigest = + AccountJwtSignerDesiredStateRepository.generationRequestDigest( + operation.operationDigest(), observationDigest, secretUid, resourceVersion); + return new SecretObservation( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + operation.expectedRecordVersion(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + secretUid, + resourceVersion, + observationDigest, + generationRequestDigest); + } + } + + private record PublicJwk(String kid, String canonicalJson, String fingerprint) {} + + private record LockedCurrent(DesiredState state, StoredGenerationOperation operation) {} + + private record StoredPromotion( + UUID operationId, + Binding binding, + int requestDigestVersion, + String requestDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String expectedPrivateResourceVersion, + String expectedPublicResourceVersion, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String apiBindingDigest, + String apiConfigRevision, + String secretUid, + String publicConfigMapUid, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String activeJwksObservedResourceVersion, + String activeJwksPublicDataDigest, + String activeJwksReceiptDigest) { + private StoredPromotion { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Promotion binding is required"); + if (requestDigestVersion != 1 + || expectedRecordVersion <= 0L + || expectedRecordVersion == Long.MAX_VALUE) { + throw new QuarantinedStateException("Promotion version fence is malformed"); + } + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "promotion target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new QuarantinedStateException("Promotion target algorithm is unsupported"); + } + requireMatch(SHA256_HEX, targetPublicKeyFingerprint, "promotion target fingerprint"); + requireMatch( + RESOURCE_VERSION, expectedPrivateResourceVersion, "expected private Secret version"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "expected public ConfigMap version"); + Objects.requireNonNull(trustFence, "Promotion trust fence is required"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, apiBindingDigest, "public API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public API config revision"); + requireUuid(secretUid, "promotion Secret UID"); + requireUuid(publicConfigMapUid, "promotion ConfigMap UID"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || expectedActiveMarkerJson == null + || expectedActiveMarkerJson.isBlank() + || expectedActiveMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException("Promotion public payload is missing or oversized"); + } + if (!Set.of("PREPARED", "COMMITTED", "ABORTED").contains(status)) { + throw new QuarantinedStateException("Promotion status is malformed"); + } + boolean noActiveJwksReceipt = + activeJwksObservedResourceVersion == null + && activeJwksPublicDataDigest == null + && activeJwksReceiptDigest == null; + boolean completeActiveJwksReceipt = + activeJwksObservedResourceVersion != null + && activeJwksPublicDataDigest != null + && activeJwksReceiptDigest != null; + if ((privatePromotionObservedResourceVersion == null) + != (privatePromotionReceiptDigest == null) + || !(noActiveJwksReceipt || completeActiveJwksReceipt)) { + throw new QuarantinedStateException("Promotion resource receipts are partial"); + } + if ((privatePromotionReceiptDigest != null && !privatePromotionDispatched) + || ("COMMITTED".equals(status) && !privatePromotionDispatched) + || ("ABORTED".equals(status) && privatePromotionDispatched)) { + throw new QuarantinedStateException( + "Promotion dispatch state is inconsistent with its receipts or terminal status"); + } + if (privatePromotionObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, + privatePromotionObservedResourceVersion, + "private promotion readback version"); + requireMatch(SHA256_HEX, privatePromotionReceiptDigest, "private promotion receipt digest"); + } + if (activeJwksObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, activeJwksObservedResourceVersion, "active JWKS readback version"); + requireMatch(SHA256_HEX, activeJwksPublicDataDigest, "active JWKS public data digest"); + requireMatch(SHA256_HEX, activeJwksReceiptDigest, "active JWKS receipt digest"); + } + } + + private static StoredPromotion create( + PromotionPreparation preparation, + DesiredState state, + StoredGenerationOperation generation, + GenerationResult result, + TrustFence trust, + Binding binding) { + if (!preparation.generationOperationId().equals(generation.operationId()) + || !preparation.generationResult().equals(result) + || !preparation + .enrollmentIdentity() + .sameStablePins(state.enrollmentIdentity().orElseThrow()) + || !generation.binding().equals(binding) + || !result.binding().equals(binding) + || !generation.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || !state.generationOperationId().equals(Optional.of(generation.operationId())) + || state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Promotion preparation is not bound to the current Account generation and enrollment"); + } + UUID promotionId = UUID.randomUUID(); + StoredPromotion unsigned = + new StoredPromotion( + promotionId, + binding, + 1, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + result.targetGeneration(), + result.targetKid(), + result.targetAlgorithm(), + result.publicKeyFingerprint(), + result.observedResourceVersion(), + preparation.expectedPublicResourceVersion(), + trust, + generation.operationId(), + generation.operationDigest(), + result.receiptDigest(), + preparation.apiBindingDigest(), + preparation.apiConfigRevision(), + result.secretUid(), + preparation.publicConfigMapUid(), + preparation.prepublicationIntentDigest(), + preparation.prepublicationReceiptDigest(), + preparation.mountedObservationDigest(), + preparation.readinessPlanDigest(), + preparation.readinessEvidenceDigest(), + preparation.expectedPublicJwksJson(), + "{}", + "PREPARED", + false, + null, + null, + null, + null, + null); + StoredPromotion signed = + new StoredPromotion( + unsigned.operationId(), + unsigned.binding(), + unsigned.requestDigestVersion(), + promotionRequestDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.targetPublicKeyFingerprint(), + unsigned.expectedPrivateResourceVersion(), + unsigned.expectedPublicResourceVersion(), + unsigned.trustFence(), + unsigned.generationOperationId(), + unsigned.generationOperationDigest(), + unsigned.generationReceiptDigest(), + unsigned.apiBindingDigest(), + unsigned.apiConfigRevision(), + unsigned.secretUid(), + unsigned.publicConfigMapUid(), + unsigned.prepublicationIntentDigest(), + unsigned.prepublicationReceiptDigest(), + unsigned.mountedObservationDigest(), + unsigned.readinessPlanDigest(), + unsigned.readinessEvidenceDigest(), + unsigned.expectedPublicJwksJson(), + "{}", + unsigned.status(), + unsigned.privatePromotionDispatched(), + null, + null, + null, + null, + null); + return new StoredPromotion( + signed.operationId(), + signed.binding(), + signed.requestDigestVersion(), + signed.requestDigest(), + signed.expectedRecordVersion(), + signed.expectedPreviousActive(), + signed.expectedPublishedActive(), + signed.targetGeneration(), + signed.targetKid(), + signed.targetAlgorithm(), + signed.targetPublicKeyFingerprint(), + signed.expectedPrivateResourceVersion(), + signed.expectedPublicResourceVersion(), + signed.trustFence(), + signed.generationOperationId(), + signed.generationOperationDigest(), + signed.generationReceiptDigest(), + signed.apiBindingDigest(), + signed.apiConfigRevision(), + signed.secretUid(), + signed.publicConfigMapUid(), + signed.prepublicationIntentDigest(), + signed.prepublicationReceiptDigest(), + signed.mountedObservationDigest(), + signed.readinessPlanDigest(), + signed.readinessEvidenceDigest(), + signed.expectedPublicJwksJson(), + activeMarkerJson(signed), + signed.status(), + signed.privatePromotionDispatched(), + null, + null, + null, + null, + null); + } + + private String operationDigestForGeneration() { + return generationOperationDigest; + } + + private boolean matchesPreparation( + PromotionPreparation preparation, + StoredGenerationOperation generation, + GenerationResult result, + EnrollmentIdentity enrollment) { + return generation.operationId().equals(preparation.generationOperationId()) + && result.equals(preparation.generationResult()) + && preparation.enrollmentIdentity().sameStablePins(enrollment) + && apiBindingDigest.equals(preparation.apiBindingDigest()) + && apiConfigRevision.equals(preparation.apiConfigRevision()) + && publicConfigMapUid.equals(preparation.publicConfigMapUid()) + && expectedPublicResourceVersion.equals(preparation.expectedPublicResourceVersion()) + && prepublicationIntentDigest.equals(preparation.prepublicationIntentDigest()) + && prepublicationReceiptDigest.equals(preparation.prepublicationReceiptDigest()) + && mountedObservationDigest.equals(preparation.mountedObservationDigest()) + && readinessPlanDigest.equals(preparation.readinessPlanDigest()) + && readinessEvidenceDigest.equals(preparation.readinessEvidenceDigest()) + && expectedPublicJwksJson.equals(preparation.expectedPublicJwksJson()) + && generationOperationId.equals(generation.operationId()) + && generationOperationDigest.equals(generation.operationDigest()) + && generationReceiptDigest.equals(result.receiptDigest()) + && secretUid.equals(result.secretUid()) + && expectedPrivateResourceVersion.equals(result.observedResourceVersion()) + && targetGeneration.equals(result.targetGeneration()) + && targetKid.equals(result.targetKid()) + && targetPublicKeyFingerprint.equals(result.publicKeyFingerprint()); + } + + private PromotionOperationEvidence publicEvidence() { + return new PromotionOperationEvidence( + operationId, + requestDigest, + expectedRecordVersion, + binding, + expectedPreviousActive, + expectedPreviousActive.map( + active -> publicFingerprintForKid(expectedPublicJwksJson, active.kid())), + expectedPublishedActive, + targetGeneration, + targetKid, + targetAlgorithm, + targetPublicKeyFingerprint, + trustFence, + generationOperationId, + generationOperationDigest, + generationReceiptDigest, + secretUid, + expectedPrivateResourceVersion, + apiBindingDigest, + apiConfigRevision, + publicConfigMapUid, + expectedPublicResourceVersion, + prepublicationIntentDigest, + prepublicationReceiptDigest, + mountedObservationDigest, + readinessPlanDigest, + readinessEvidenceDigest, + expectedPublicJwksJson, + expectedActiveMarkerJson, + status, + privatePromotionDispatched, + Optional.ofNullable(privatePromotionObservedResourceVersion), + Optional.ofNullable(privatePromotionReceiptDigest), + Optional.ofNullable(activeJwksObservedResourceVersion), + Optional.ofNullable(activeJwksPublicDataDigest), + Optional.ofNullable(activeJwksReceiptDigest)); + } + } + + public record PreparedGenerationEvidence( + DesiredState desiredState, + PromotionOperationEvidence promotion, + GenerationResult generationResult) { + public PreparedGenerationEvidence { + Objects.requireNonNull(desiredState); + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + if (!"PREPARED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId())) { + throw new QuarantinedStateException("Prepared generation evidence is inconsistent"); + } + } + } + + /** Exact current owner-readback values required to freeze one PREPARED operation. */ + public record PromotionPreparation( + UUID generationOperationId, + GenerationResult generationResult, + EnrollmentIdentity enrollmentIdentity, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson) { + public PromotionPreparation { + requireOperationId(generationOperationId); + Objects.requireNonNull(generationResult, "Persisted generation result is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned Account enrollment is required"); + requireMatch(SHA256_HEX, apiBindingDigest, "promotion API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "promotion API config revision"); + requireUuid(publicConfigMapUid, "promotion public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "promotion ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion public projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionObservation( + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String jwksJson, + String activeMarkerJson) { + public ActiveJwksPromotionObservation { + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || activeMarkerJson == null + || activeMarkerJson.isBlank() + || activeMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionReceipt( + UUID promotionOperationId, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public ActiveJwksPromotionReceipt { + requireOperationId(promotionOperationId); + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + requireMatch(SHA256_HEX, publicDataDigest, "active public ConfigMap data digest"); + requireMatch(SHA256_HEX, receiptDigest, "active public ConfigMap receipt digest"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + } + + private static ActiveJwksPromotionReceipt from( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + observation.jwksJson(), observation.activeMarkerJson()); + return create( + promotion, + observation.configMapUid(), + observation.priorResourceVersion(), + observation.observedResourceVersion(), + dataDigest); + } + + private static ActiveJwksPromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.activeJwksObservedResourceVersion() == null + || promotion.activeJwksPublicDataDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no active JWKS receipt"); + } + ActiveJwksPromotionReceipt calculated = + create( + promotion, + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest()); + if (!calculated.receiptDigest().equals(promotion.activeJwksReceiptDigest())) { + throw new QuarantinedStateException("Committed active JWKS receipt digest is invalid"); + } + return calculated; + } + + private static ActiveJwksPromotionReceipt create( + StoredPromotion promotion, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String dataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); + preimage.put("configMapUid", configMapUid); + preimage.put("priorResourceVersion", priorResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + return new ActiveJwksPromotionReceipt( + promotion.operationId(), + configMapUid, + priorResourceVersion, + observedResourceVersion, + dataDigest, + digest(preimage)); + } + } + + /** Durable non-authorizing result for Account's current committed active signer. */ + public record CommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + DesiredState desiredState, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public CommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(desiredState); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || desiredState.durableActive().filter(target::equals).isEmpty() + || desiredState.publishedActive().filter(target::equals).isEmpty() + || desiredState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Committed signer evidence is inconsistent"); + } + } + } + + public record AbortedPromotion( + UUID operationId, + long desiredStateVersion, + Optional durableActive, + Optional publishedActive) { + public AbortedPromotion { + requireOperationId(operationId); + if (desiredStateVersion <= 0) + throw new IllegalArgumentException("Aborted state version is invalid"); + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Aborted signer operation changed active fences"); + } + } + } + + /** Public-only immutable promotion row needed by the materializer and Account reconciler. */ + public record PromotionOperationEvidence( + UUID operationId, + String requestDigest, + long expectedRecordVersion, + Binding binding, + Optional expectedPreviousActive, + Optional expectedPreviousPublicKeyFingerprint, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String secretUid, + String expectedPrivateResourceVersion, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + Optional privatePromotionObservedResourceVersion, + Optional privatePromotionReceiptDigest, + Optional activeJwksObservedResourceVersion, + Optional activeJwksPublicDataDigest, + Optional activeJwksReceiptDigest) { + public PromotionOperationEvidence { + Objects.requireNonNull(operationId); + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + Objects.requireNonNull(binding); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPreviousPublicKeyFingerprint = + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + if (expectedPreviousActive.isPresent() != expectedPreviousPublicKeyFingerprint.isPresent()) { + throw new QuarantinedStateException("Promotion prior public identity is incomplete"); + } + expectedPreviousPublicKeyFingerprint.ifPresent( + value -> requireMatch(SHA256_HEX, value, "prior public-key fingerprint")); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + privatePromotionObservedResourceVersion = + Objects.requireNonNull(privatePromotionObservedResourceVersion); + privatePromotionReceiptDigest = Objects.requireNonNull(privatePromotionReceiptDigest); + activeJwksObservedResourceVersion = Objects.requireNonNull(activeJwksObservedResourceVersion); + activeJwksPublicDataDigest = Objects.requireNonNull(activeJwksPublicDataDigest); + activeJwksReceiptDigest = Objects.requireNonNull(activeJwksReceiptDigest); + } + } + + public record PublicKeyIdentity(String generation, String kid, String publicKeyFingerprint) { + public PublicKeyIdentity { + parseGeneration(generation); + requireMatch(KID, kid, "observed public key kid"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "observed public key fingerprint"); + } + } + + public record PrivatePromotionObservation( + UUID promotionOperationId, + String promotionRequestDigest, + UUID generationOperationId, + String generationOperationDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + PublicKeyIdentity current, + Optional previous, + List resultingSlots) { + public PrivatePromotionObservation { + requireOperationId(promotionOperationId); + requireMatch(SHA256_HEX, promotionRequestDigest, "promotion request digest"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret version"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret version"); + Objects.requireNonNull(current); + previous = Objects.requireNonNull(previous); + resultingSlots = List.copyOf(resultingSlots); + if (expectedPriorResourceVersion.equals(observedResourceVersion) + || !(resultingSlots.equals(List.of("current")) + || resultingSlots.equals(List.of("current", "previous")))) { + throw new QuarantinedStateException("Private promotion readback identity is malformed"); + } + } + } + + public record PrivatePromotionReceipt( + UUID promotionOperationId, + UUID generationOperationId, + String observedResourceVersion, + String receiptDigest) { + public PrivatePromotionReceipt { + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "private promotion readback version"); + requireMatch(SHA256_HEX, receiptDigest, "private promotion receipt digest"); + } + + private static PrivatePromotionReceipt from( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", 1); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("secretResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", observation.secretUid()); + preimage.put("expectedPriorResourceVersion", observation.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", observation.observedResourceVersion()); + preimage.put("action", "PROMOTE_PENDING"); + preimage.put("resultingSlots", observation.resultingSlots()); + preimage.put("current", publicKeyIdentityMap(observation.current())); + preimage.put( + "previous", + observation + .previous() + .map(AccountJwtSignerDesiredStateRepository::publicKeyIdentityMap) + .orElseGet(() -> Map.of("present", false))); + return new PrivatePromotionReceipt( + promotion.operationId(), + promotion.generationOperationId(), + observation.observedResourceVersion(), + digest(preimage)); + } + + private static PrivatePromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.privatePromotionObservedResourceVersion() == null + || promotion.privatePromotionReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no private promotion receipt"); + } + Optional previous = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid( + promotion.expectedPublicJwksJson(), active.kid()))); + PrivatePromotionReceipt calculated = + from( + promotion, + new PrivatePromotionObservation( + promotion.operationId(), + promotion.requestDigest(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.secretUid(), + promotion.expectedPrivateResourceVersion(), + promotion.privatePromotionObservedResourceVersion(), + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()), + previous, + previous.isPresent() ? List.of("current", "previous") : List.of("current"))); + if (!calculated.receiptDigest().equals(promotion.privatePromotionReceiptDigest())) { + throw new QuarantinedStateException( + "Committed private promotion receipt digest is invalid"); + } + return calculated; + } + } + + private static Map publicKeyIdentityMap(PublicKeyIdentity identity) { + return Map.of( + "generation", identity.generation(), + "kid", identity.kid(), + "publicKeyFingerprint", identity.publicKeyFingerprint()); + } + + public record PreparedPromotion(UUID operationId, String requestDigest, String status) { + public PreparedPromotion { + requireOperationId(operationId); + requireMatch(SHA256_HEX, requestDigest, "prepared promotion digest"); + if (!"PREPARED".equals(status)) { + throw new IllegalArgumentException("Only PREPARED JWT signer operations are represented"); + } + } + } + + private static String generationRequestDigest( + String operationDigest, String observationDigest, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", operationDigest, + "observationDigest", observationDigest, + "secretUid", secretUid, + "expectedPriorResourceVersion", resourceVersion, + "target", "pending")); + } + + public static class MissingDesiredStateException extends IllegalStateException { + public MissingDesiredStateException(String environmentId) { + super("Account JWT signer desired state is missing for environment " + environmentId); + } + } + + public static class MissingGenerationOperationException extends IllegalStateException { + public MissingGenerationOperationException(String message) { + super(message); + } + } + + public static class MissingGenerationObservationException extends IllegalStateException { + public MissingGenerationObservationException(String message) { + super(message); + } + } + + public static class StaleGenerationOperationException extends IllegalStateException { + public StaleGenerationOperationException(String message) { + super(message); + } + } + + public static class BindingMismatchException extends IllegalStateException { + public BindingMismatchException(String message) { + super(message); + } + } + + public static class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + + public QuarantinedStateException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class PromotionPrerequisitesIncompleteException extends IllegalStateException { + public PromotionPrerequisitesIncompleteException(String message) { + super(message); + } + } + + public static class NoPreparedPromotionException extends IllegalStateException { + public NoPreparedPromotionException() { + super("Account has no PREPARED JWT signer promotion"); + } + } + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java new file mode 100644 index 0000000000..4c3558b831 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -0,0 +1,280 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Immutable persistence for an Account-observed, non-authorizing validator inventory snapshot. The + * table stores only the source's closed canonical public/runtime observation, never API response + * objects or credentials. + */ +@Repository +public class AccountJwtValidatorInventoryRepository { + public static final int MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String TABLE = "account_jwt_validator_inventory_snapshots"; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtValidatorInventoryRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Inserts once or proves that a same-digest retry reads back the exact immutable bytes. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot persistOrReadback( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + requireWritableAccountTransaction(); + Objects.requireNonNull(snapshot, "Owner-observed inventory snapshot is required"); + requireBinding(snapshot, binding, trustFence); + byte[] canonicalBytes = snapshot.canonicalBytes(); + requireSnapshotBytes(canonicalBytes, snapshot.digest()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (snapshot_digest, environment_id, cluster_id, cluster_incarnation_uid, " + + "kubernetes_namespace, namespace_uid, api_binding_revision, api_binding_digest, " + + "inventory_binding_revision, inventory_binding_digest, observed_at, canonical_snapshot) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (snapshot_digest) DO NOTHING", + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + UUID.fromString(snapshot.clusterIncarnationUid()), + snapshot.namespace(), + UUID.fromString(snapshot.namespaceUid()), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + snapshot.observedAt().toString(), + canonicalBytes); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR UPDATE", snapshot.digest()); + StoredSnapshot stored = decode(row); + requireSameSnapshot(snapshot, stored); + requireBinding(stored, binding, trustFence); + return stored; + } + + /** Reads the exact previously persisted snapshot and rechecks its Account binding. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot readRequired(String digest, Binding binding, TrustFence trustFence) { + requireAccountTransaction(); + if (digest == null || !DIGEST.matcher(digest).matches()) { + throw new InventorySnapshotUnavailableException(); + } + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR KEY SHARE", digest); + StoredSnapshot stored = decode(row); + requireBinding(stored, binding, trustFence); + return stored; + } + + private static StoredSnapshot decode(Record row) { + if (row == null) { + throw new InventorySnapshotUnavailableException(); + } + try { + String digest = row.get("snapshot_digest", String.class); + byte[] bytes = row.get("canonical_snapshot", byte[].class); + requireSnapshotBytes(bytes, digest); + StoredSnapshot stored = + new StoredSnapshot( + digest, + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + Instant.parse(row.get("observed_at", String.class)), + bytes); + return stored; + } catch (InventorySnapshotUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSnapshotBytes(byte[] bytes, String digest) { + if (bytes == null + || bytes.length < 2 + || bytes.length > MAX_SNAPSHOT_BYTES + || digest == null + || !DIGEST.matcher(digest).matches() + || !digest(bytes).equals(digest)) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapshot actual) { + // A content digest can be observed again later. Keep the first persisted timestamp immutable; + // callers separately use the fresh observation's timestamp for the bounded freshness check. + if (!expected.digest().equals(actual.digest()) + || !expected.environmentId().equals(actual.environmentId()) + || !expected.clusterId().equals(actual.clusterId()) + || !expected.clusterIncarnationUid().equals(actual.clusterIncarnationUid()) + || !expected.namespace().equals(actual.namespace()) + || !expected.namespaceUid().equals(actual.namespaceUid()) + || !expected.apiBindingRevision().equals(actual.apiBindingRevision()) + || !expected.apiBindingDigest().equals(actual.apiBindingDigest()) + || !expected.inventoryBindingRevision().equals(actual.inventoryBindingRevision()) + || !expected.inventoryBindingDigest().equals(actual.inventoryBindingDigest()) + || !MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + StoredSnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + public record StoredSnapshot( + String digest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + Instant observedAt, + byte[] canonicalBytes) { + public StoredSnapshot { + Objects.requireNonNull(digest); + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(clusterIncarnationUid); + Objects.requireNonNull(namespace); + Objects.requireNonNull(namespaceUid); + Objects.requireNonNull(apiBindingRevision); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(inventoryBindingRevision); + Objects.requireNonNull(inventoryBindingDigest); + Objects.requireNonNull(observedAt); + canonicalBytes = canonicalBytes.clone(); + requireSnapshotBytes(canonicalBytes, digest); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StoredSnapshot that)) { + return false; + } + return digest.equals(that.digest) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && observedAt.equals(that.observedAt) + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + digest, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + observedAt) + + Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventorySnapshotUnavailableException extends RuntimeException { + public InventorySnapshotUnavailableException() { + super("Account validator inventory snapshot is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java new file mode 100644 index 0000000000..52dc1e045e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -0,0 +1,848 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account verification of a signed control-ui actor against committed issuance, + * Coordination, protected signer/JWKS state, and current Account tenant membership sources. + * + *

The returned object is authenticated-current actor evidence only. This class does not issue or + * redeem operator references, select a privileged route, or turn a creator grant into owner + * authority. It deliberately denies global-role claims; callers must perform the approved route + * predicate separately against this current tenant-scoped evidence. + */ +public final class AccountControlUiCurrentActorVerifier { + private static final String ISSUER = "firemud-account-service"; + private static final int MAX_BUNDLE_BYTES = 131072; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Set SIGNER_RECEIPT_FIELDS = + Set.of( + "schema", + "environmentId", + "clusterId", + "namespace", + "clusterIncarnationUid", + "namespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision", + "promotionOperationId", + "promotionRequestDigest", + "generationOperationId", + "signerGeneration", + "kid", + "algorithm", + "publicKeyFingerprint", + "privateReceiptDigest", + "privateResourceVersion", + "publicReceiptDigest", + "publicResourceVersion", + "publicConfigMapUid", + "publicDataDigest"); + private static final Set PENDING_RECEIPT_FIELDS = + Set.of( + "schema", + "tokenHash", + "recordDigest", + "expiryMillis", + "aclIdentity", + "localAofCount", + "replicaAofCount"); + private static final Set BUNDLE_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints", + "roleEvidence"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + private static final ExplicitRouteProfilePolicy POLICY = + new ExplicitRouteProfilePolicy( + "account-control-ui-current-actor", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ISSUER, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + Set.of(), + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + + private final AccountJwtJwksTrustedSource publicJwks; + private final AccountJwtSignerDesiredStateRepository signerStates; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding jwksApiBinding; + private final AccountControlUiRegistryReader registry; + private final AccountControlUiCommittedIssuanceRepository issuances; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository membershipPairs; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + private final AccountAuthorityOutboxRepository outbox; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories are shared owner services; they must retain their transaction and current-state identity rather than be copied.") + public AccountControlUiCurrentActorVerifier( + AccountJwtJwksTrustedSource publicJwks, + AccountJwtSignerDesiredStateRepository signerStates, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksApiBinding jwksApiBinding, + AccountControlUiRegistryReader registry, + AccountControlUiCommittedIssuanceRepository issuances, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthorityGenerationRepository generations, + AccountTenantAuthorityEventRepository tenantEvents, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository membershipPairs, + AccountTenantMembershipRoleSnapshotRepository roleSnapshots, + AccountAuthorityOutboxRepository outbox, + PlatformTransactionManager transactionManager, + Clock clock) { + this.publicJwks = Objects.requireNonNull(publicJwks); + this.signerStates = Objects.requireNonNull(signerStates); + this.materializerTrust = Objects.requireNonNull(materializerTrust); + this.jwksApiBinding = Objects.requireNonNull(jwksApiBinding); + this.registry = Objects.requireNonNull(registry); + this.issuances = Objects.requireNonNull(issuances); + this.sourceEvidence = Objects.requireNonNull(sourceEvidence); + this.generations = Objects.requireNonNull(generations); + this.tenantEvents = Objects.requireNonNull(tenantEvents); + this.memberships = Objects.requireNonNull(memberships); + this.membershipPairs = Objects.requireNonNull(membershipPairs); + this.roleSnapshots = Objects.requireNonNull(roleSnapshots); + this.outbox = Objects.requireNonNull(outbox); + this.clock = Objects.requireNonNull(clock); + accountTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + accountTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + accountTransaction.setReadOnly(false); + } + + /** Verifies one signed actor for its selected canonical tenant; no authorization is returned. */ + public CurrentActor verify(String compactJwt, UUID selectedTenant) { + outsideSql(); + requireTenant(selectedTenant); + byte[] compactBytes = compactBytes(compactJwt); + SourceIdentity pin = publicJwks.sourceIdentity(); + AccountPublicJwksCache cache = + new AccountPublicJwksCache(publicJwks, pin, clock, Duration.ofSeconds(30)); + VerifiedClaims signed = + new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY); + PublicJwksSnapshot currentJwks = publicJwks.load(); + String tokenHash = sha256(compactBytes); + byte[] activeRegistry = registry.readActive(tokenHash); + + CurrentActor result = + accountTransaction.execute( + ignored -> + verifyOwnerState( + tokenHash, selectedTenant, signed, pin, currentJwks, activeRegistry)); + if (result == null) { + throw denied(); + } + return result; + } + + private CurrentActor verifyOwnerState( + String tokenHash, + UUID selectedTenant, + VerifiedClaims signed, + SourceIdentity pin, + PublicJwksSnapshot currentJwks, + byte[] activeRegistry) { + Map claims = signed.claims(); + UUID accountId = uuid(claims.get("accountId")); + UUID tokenTenant = selectedScopedTenant(claims, selectedTenant); + if (!selectedTenant.equals(tokenTenant) || claims.containsKey("globalRoles")) { + throw denied(); + } + CommittedIssuance issuance = + issuances + .readCommitted(tokenHash) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord(activeRegistry, tokenHash); + if (!ISSUER.equals(claims.get("iss")) + || !claims.get("sub").equals(accountId.toString()) + || !issuance.tokenHash().equals(tokenHash) + || !issuance.accountId().equals(accountId) + || !issuance.tenantId().equals(selectedTenant) + || !issuance.tokenJti().equals(uuid(claims.get("jti"))) + || !issuance.requestId().equals(uuid(registryRecord.get("requestId"))) + || !issuance.operationId().equals(uuid(registryRecord.get("operationId"))) + || !Arrays.equals(activeRegistry, issuance.activeRegistry()) + || !Arrays.equals(canonicalBytes(claims), issuance.claims()) + || !signed.keyId().equals(registryRecord.get("kid")) + || !accountId.toString().equals(registryRecord.get("accountId")) + || !claims.get("jti").equals(registryRecord.get("jti")) + || !canonicalMapEquals(registryRecord.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals( + registryRecord.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals( + registryRecord.get("tokenGeneration"), positiveLong(claims.get("tokenGeneration"))) + || !numericEquals( + registryRecord.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !numericEquals(claims.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("exp"), issuance.expiresAtEpochSecond()) + || !numericEquals(registryRecord.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("exp"), issuance.expiresAtEpochSecond()) + || !Arrays.equals(issuance.pendingRegistry(), derivePendingRegistry(activeRegistry))) { + throw denied(); + } + requireBundle(issuance, claims, registryRecord); + requirePendingReceipt(issuance); + requireSignerReceipt(issuance, signed.keyId(), pin, currentJwks); + return requireCurrentAccountAuthority(issuance, claims, selectedTenant, tokenHash); + } + + private void requireBundle( + CommittedIssuance issuance, Map claims, Map registryRecord) { + Map storedClaims = parseCanonicalObject(issuance.claims(), 16384); + Map bundle = parseCanonicalObject(issuance.bundle(), MAX_BUNDLE_BYTES); + Map bundleRef = object(bundle.get("bundleRef")); + Map scope = object(bundle.get("scope")); + Map operation = object(bundle.get("operation")); + Map tokenIdentity = object(bundle.get("tokenIdentity")); + Map roleEvidence = object(bundle.get("roleEvidence")); + if (!bundle.keySet().equals(BUNDLE_FIELDS) + || !bundleRef + .keySet() + .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !scope.keySet().equals(Set.of("kind", "accountId", "tenantIds")) + || !operation + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId")) + || !tokenIdentity.keySet().equals(Set.of("jti", "tokenGeneration", "iat", "nbf", "exp")) + || !roleEvidence.keySet().equals(Set.of("scopedRoles", "freshnessSource")) + || !Arrays.equals(canonicalBytes(claims), canonicalBytes(storedClaims)) + || !"account-auth-evidence-bundle/v1".equals(bundle.get("schema")) + || !ISSUER.equals(bundle.get("issuer")) + || !"control-ui".equals(bundle.get("profile")) + || !"control-ui".equals(bundle.get("audience")) + || !issuance.operationId().toString().equals(operation.get("operationId")) + || !issuance.requestId().toString().equals(operation.get("requestId")) + || !issuance.requestDigest().equals(operation.get("requestDigest")) + || !issuance.accountId().toString().equals(operation.get("accountId")) + || !issuance.callerWorkload().equals(operation.get("callerWorkload")) + || !issuance.callerContextId().toString().equals(operation.get("callerContextId")) + || !issuance.accountId().toString().equals(scope.get("accountId")) + || !List.of(issuance.tenantId().toString()).equals(scope.get("tenantIds")) + || !"TENANT".equals(scope.get("kind")) + || !canonicalMapEquals(bundle.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals(bundle.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals(bundle.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !canonicalMapEquals( + bundle.get("authoritySourceVersions"), registryRecord.get("authoritySourceVersions")) + || !canonicalMapEquals(tokenIdentity, tokenIdentity(claims)) + || !canonicalMapEquals(roleEvidence.get("scopedRoles"), claims.get("scopedRoles"))) { + throw denied(); + } + parseCanonicalObject(issuance.source(), 131072); + String sourceIdentity = sha256(issuance.source()); + if (!sourceIdentity.equals(bundle.get("snapshotIdentity")) + || !sourceIdentity.equals(roleEvidence.get("freshnessSource"))) { + throw denied(); + } + Map expectedReference = new LinkedHashMap<>(bundleRef); + expectedReference.put("canonicalSha256", sha256(issuance.bundle())); + if (!canonicalMapEquals(expectedReference, registryRecord.get("authEvidenceBundle"))) { + throw denied(); + } + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceIdentity); + if (!sha256(canonicalBytes(evaluation)).equals(bundle.get("evaluationIdentity"))) { + throw denied(); + } + } + + private void requirePendingReceipt(CommittedIssuance issuance) { + Map receipt = parseCanonicalObject(issuance.pendingReceipt(), 8192); + if (!receipt.keySet().equals(PENDING_RECEIPT_FIELDS) + || !"account-control-ui-pending-readback/v1".equals(receipt.get("schema")) + || !issuance.tokenHash().equals(receipt.get("tokenHash")) + || !sha256(issuance.pendingRegistry()).equals(receipt.get("recordDigest")) + || !"account_coord_app".equals(receipt.get("aclIdentity")) + || !numericEquals(receipt.get("expiryMillis"), issuance.expiryMillis()) + || !atLeastOne(receipt.get("localAofCount")) + || !atLeastOne(receipt.get("replicaAofCount"))) { + throw denied(); + } + } + + private void requireSignerReceipt( + CommittedIssuance issuance, + String verifiedKid, + SourceIdentity pin, + PublicJwksSnapshot currentJwks) { + Map receipt = parseCanonicalObject(issuance.signerReceipt(), 65536); + Optional fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint(currentJwks, pin, verifiedKid); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord( + issuance.activeRegistry(), issuance.tokenHash()); + if (!receipt.keySet().equals(SIGNER_RECEIPT_FIELDS) + || !"account-control-ui-committed-signer/v1".equals(receipt.get("schema")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision")) + || !verifiedKid.equals(receipt.get("kid")) + || !verifiedKid.equals(registryRecord.get("kid")) + || !"RS256".equals(receipt.get("algorithm")) + || !fingerprint.orElse("").equals(receipt.get("publicKeyFingerprint")) + || !registryRecord.get("signerGeneration").equals(receipt.get("signerGeneration")) + || !issuance.operationId().toString().equals(registryRecord.get("operationId")) + || !issuance.requestId().toString().equals(registryRecord.get("requestId")) + || !issuance.requestDigest().equals(registryRecord.get("requestDigest")) + || !sha256(issuance.signerReceipt()) + .equals(registryRecord.get("originalSignerReceiptDigest")) + || !DIGEST.matcher(text(receipt.get("trustBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("apiBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("promotionRequestDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("privateReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicDataDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicKeyFingerprint"))).matches()) { + throw denied(); + } + requireOriginalCommittedSigner(receipt, verifiedKid); + } + + private void requireOriginalCommittedSigner(Map receipt, String verifiedKid) { + var materializer = + materializerTrust.current().orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var api = jwksApiBinding.current(); + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || !text(receipt.get("apiBindingDigest")).equals(api.bindingDigest()) + || !text(receipt.get("apiConfigRevision")).equals(api.configRevision()) + || !text(receipt.get("trustBindingDigest")).equals(materializer.bindingDigest()) + || !text(receipt.get("trustConfigRevision")).equals(materializer.configRevision())) { + throw denied(); + } + Binding binding = + new Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + var original = + signerStates + .readOriginalCommittedSigner( + binding, + trust, + api.bindingDigest(), + api.configRevision(), + uuid(receipt.get("promotionOperationId")), + uuid(receipt.get("generationOperationId"))) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var promotion = original.promotion(); + var generation = original.generationResult(); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().toString().equals(receipt.get("promotionOperationId")) + || !promotion.requestDigest().equals(receipt.get("promotionRequestDigest")) + || !generation.operationId().toString().equals(receipt.get("generationOperationId")) + || !verifiedKid.equals(generation.targetKid()) + || !generation.targetGeneration().equals(receipt.get("signerGeneration")) + || !"RS256".equals(generation.targetAlgorithm()) + || !generation.publicKeyFingerprint().equals(receipt.get("publicKeyFingerprint")) + || !original.privateReceipt().receiptDigest().equals(receipt.get("privateReceiptDigest")) + || !original + .privateReceipt() + .observedResourceVersion() + .equals(receipt.get("privateResourceVersion")) + || !original.publicReceipt().receiptDigest().equals(receipt.get("publicReceiptDigest")) + || !original + .publicReceipt() + .observedResourceVersion() + .equals(receipt.get("publicResourceVersion")) + || !original.publicReceipt().configMapUid().equals(receipt.get("publicConfigMapUid")) + || !original.publicReceipt().publicDataDigest().equals(receipt.get("publicDataDigest"))) { + throw denied(); + } + } + + private CurrentActor requireCurrentAccountAuthority( + CommittedIssuance issuance, Map claims, UUID tenantId, String tokenHash) { + UUID accountId = issuance.accountId(); + IssuerAccountSourceSnapshot source = + sourceEvidence.readCurrentIssuerAccountSources(ISSUER, accountId); + CompositeSnapshot snapshot = + generations.readCompositeSnapshot(ISSUER, accountId, List.of(tenantId), List.of(tenantId)); + if (source.issuer().generation() != snapshot.issuer().generation() + || source.issuer().sourceVersion() != snapshot.issuer().sourceVersion() + || source.account().generation() != snapshot.account().generation() + || source.account().sourceVersion() != snapshot.account().sourceVersion() + || !source.issuanceFence().equals(snapshot.issuanceFence())) { + throw denied(); + } + var tenantState = only(snapshot.tenants(), "tenant authority"); + var membershipState = only(snapshot.memberships(), "membership authority"); + Event currentTenant = tenantEvents.readCurrentByTenant(tenantId); + if (!tenantId.equals(currentTenant.tenantId()) + || currentTenant.tenantAuthorityGeneration() != tenantState.generation() + || currentTenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion()) { + throw denied(); + } + + PairAuthority pair = + membershipPairs + .readPositive(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + AccountTenantMembership membership = + memberships + .findFreshMembership(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.lastTransitionInvalidated() + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || !accountId.equals(membership.getAccount().getAccountUuid()) + || !tenantId.equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || membership.getMembershipVersion() != pair.membershipVersion() + || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || pair.membershipAuthorityGeneration() != membershipState.generation()) { + throw denied(); + } + MembershipEvent currentMembershipEvent = + requireCurrentMembershipEvent(accountId, tenantId, pair, membershipState.generation()); + RoleSnapshot roles = + roleSnapshots + .findForCanonicalUpdate( + accountId, + tenantId, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!roles.roles().equals(currentMembershipEvent.roles())) { + throw denied(); + } + requireClaimsCurrent( + claims, accountId, tenantId, source, snapshot, currentTenant, pair, membership, roles); + return new CurrentActor( + accountId, + tenantId, + issuance.operationId(), + tokenHash, + roles.roles(), + snapshot.issuer().generation(), + snapshot.account().generation(), + tenantState.generation(), + membershipState.generation(), + membership.getMembershipVersion(), + snapshot.issuanceFence().value()); + } + + private MembershipEvent requireCurrentMembershipEvent( + UUID accountId, UUID tenantId, PairAuthority pair, long membershipGeneration) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var stored = + outbox + .findEvent(streamKey, pair.eventSequence()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + if (!stored.outboxStreamKey().equals(streamKey) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(event.outboxSequence()) + || !pair.eventId().equals(event.eventId()) + || !pair.eventDigest().equals(event.eventDigest()) + || !accountId.toString().equals(event.accountId()) + || !tenantId.toString().equals(event.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(event.membershipVersion().get(tenantId.toString())) + || !Long.toString(membershipGeneration).equals(event.membershipAuthorityGeneration()) + || !"ACTIVE".equals(event.membershipLifecycleState()) + || event.callerBoundAuthorityInvalidated() != pair.lastTransitionInvalidated()) { + throw denied(); + } + return event; + } + + private void requireClaimsCurrent( + Map claims, + UUID accountId, + UUID tenantId, + IssuerAccountSourceSnapshot source, + CompositeSnapshot snapshot, + Event tenantEvent, + PairAuthority pair, + AccountTenantMembership membership, + RoleSnapshot roles) { + Map tuple = object(claims.get("authorityTuple")); + Map tenantGenerations = + Map.of(tenantId.toString(), only(snapshot.tenants(), "tenant").generation()); + Map membershipGenerations = + Map.of(tenantId.toString(), pair.membershipAuthorityGeneration()); + Map membershipVersions = Map.of(tenantId.toString(), pair.membershipVersion()); + Map expectedTuple = new LinkedHashMap<>(); + expectedTuple.put("issuerAuthGeneration", snapshot.issuer().generation()); + expectedTuple.put("accountAuthorityGeneration", snapshot.account().generation()); + expectedTuple.put("tenantAuthorityGeneration", tenantGenerations); + expectedTuple.put("membershipAuthorityGeneration", membershipGenerations); + expectedTuple.put("privateRealmGrantVersions", List.of()); + source + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + expectedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + if (tuple.containsKey("tenantBillingCutoff")) { + expectedTuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", + tenantEvent.tenantBillingSequence(), + "outboxStreamKey", + tenantEvent.tenantBillingStreamKey(), + "outboxSequence", + tenantEvent.outboxSequence()))); + } + Map scoped = object(claims.get("scopedRoles")); + if (!numericEquals(tuple.get("issuerAuthGeneration"), snapshot.issuer().generation()) + || !numericEquals(tuple.get("accountAuthorityGeneration"), snapshot.account().generation()) + || !canonicalMapEquals(tuple.get("tenantAuthorityGeneration"), tenantGenerations) + || !canonicalMapEquals(tuple.get("membershipAuthorityGeneration"), membershipGenerations) + || !canonicalMapEquals(tuple, expectedTuple) + || !canonicalMapEquals(claims.get("membershipVersion"), membershipVersions) + || !numericEquals(claims.get("issuanceFence"), snapshot.issuanceFence().value()) + || !canonicalMapEquals(scoped, Map.of(tenantId.toString(), roles.roles())) + || membership.getMembershipVersion() != pair.membershipVersion() + || !accountId.equals(membership.getAccount().getAccountUuid())) { + throw denied(); + } + } + + private static byte[] derivePendingRegistry(byte[] activeBytes) { + Map active = + parseCanonicalObject(activeBytes, AccountControlUiRegistryReader.MAX_RECORD_BYTES); + if (!"active".equals(active.get("state")) + || !Integer.valueOf(2).equals(number(active.get("registryVersion")))) { + throw denied(); + } + Map pending = new LinkedHashMap<>(active); + pending.put("state", "pending"); + pending.put("registryVersion", 1); + return canonicalBytes(pending); + } + + private static Map tokenIdentity(Map claims) { + Map identity = new LinkedHashMap<>(); + identity.put("jti", claims.get("jti")); + identity.put("tokenGeneration", claims.get("tokenGeneration")); + identity.put("iat", claims.get("iat")); + identity.put("nbf", claims.get("nbf")); + identity.put("exp", claims.get("exp")); + return identity; + } + + private static UUID selectedScopedTenant(Map claims, UUID selectedTenant) { + Map roles = object(claims.get("scopedRoles")); + if (!roles.keySet().equals(Set.of(selectedTenant.toString()))) { + throw denied(); + } + return selectedTenant; + } + + private static AccountAuthorityGenerationRepository.ScopeState only( + List states, String label) { + if (states == null || states.size() != 1) { + throw denied(); + } + return states.getFirst(); + } + + private static Map parseCanonicalObject(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(bytes, OBJECT); + if (fields == null) { + throw denied(); + } + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) { + throw denied(); + } + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String text)) { + throw denied(); + } + result.put(text, item); + }); + return result; + } + + private static boolean canonicalMapEquals(Object first, Object second) { + return Arrays.equals(canonicalBytes(first), canonicalBytes(second)); + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw denied(); + } + } + + private static boolean numericEquals(Object actual, long expected) { + return actual instanceof Number number && number.toString().equals(Long.toString(expected)); + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static long positiveLong(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L) { + throw denied(); + } + return parsed; + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static boolean atLeastOne(Object value) { + return value instanceof Number number + && number.toString().matches("[1-9][0-9]{0,2}") + && number.longValue() >= 1L; + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw denied(); + } + } + + private static byte[] compactBytes(String compactJwt) { + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16384 + || compactJwt.codePoints().anyMatch(codePoint -> codePoint > 0x7f)) { + throw denied(); + } + return compactJwt.getBytes(StandardCharsets.US_ASCII); + } + + private static void requireTenant(UUID tenant) { + if (tenant == null + || tenant.getMostSignificantBits() == 0L && tenant.getLeastSignificantBits() == 0L) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT and Coordination reads must precede SQL ownership"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Current Account control-ui actor evidence unavailable"); + } + + /** + * Identity and current source tuple only. It is not a route authorization or a reference grant. + */ + public record CurrentActor( + UUID accountId, + UUID tenantId, + UUID issuanceOperationId, + String tokenHash, + List currentTenantRoles, + long issuerGeneration, + long accountGeneration, + long tenantGeneration, + long membershipGeneration, + long membershipVersion, + long issuanceFence) { + public CurrentActor { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(issuanceOperationId); + if (tokenHash == null || !DIGEST.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Control-ui actor token identity is invalid"); + } + currentTenantRoles = List.copyOf(currentTenantRoles); + if (issuerGeneration <= 0L + || accountGeneration <= 0L + || tenantGeneration <= 0L + || membershipGeneration <= 0L + || membershipVersion <= 0L + || issuanceFence <= 0L) { + throw new IllegalArgumentException("Control-ui current authority values must be positive"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java new file mode 100644 index 0000000000..8246f90998 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.sync.RedisCommands; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +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.json.Rfc8785CanonicalJson; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account Coordination view of one committed control-ui token record. + * + *

This class is deliberately not a Spring bean and contains no Redis mutation path. A caller + * must supply Account's protected pinned connection provider; each read proves the live ACL user + * and exact physical cleanup deadline on that same non-reconnecting connection. Registry presence + * is only one input to Account's committed issuance/current-authority verification. + */ +public final class AccountControlUiRegistryReader { + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + public static final int MAX_RECORD_BYTES = 32 * 1024; + + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "issuer", + "profile", + "type", + "audience", + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "operationId", + "requestId", + "requestDigest", + "state", + "authoritySourceVersions", + "authEvidenceBundle", + "originalSignerReceiptDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private final AccountCoordinationPinnedConnectionProvider connections; + + public AccountControlUiRegistryReader(AccountCoordinationPinnedConnectionProvider connections) { + this.connections = + Objects.requireNonNull(connections, "private Account Coordination is required"); + } + + /** Reads and validates one active registry value without holding an Account SQL transaction. */ + public byte[] readActive(String tokenHash) { + outsideSql(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + RedisCommands commands = connection.sync(); + if (!REQUIRED_ACL_IDENTITY.equals(commands.aclWhoami())) { + throw denied(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] exact = commands.get(key); + Map record = parseActiveRecord(exact, tokenHash); + long expiresAtMillis = checkedExpiryMillis(record.get("exp")); + Long physicalExpiry = commands.pexpiretime(key); + if (physicalExpiry == null || physicalExpiry.longValue() != expiresAtMillis) { + throw denied(); + } + return exact.clone(); + } catch (RuntimeException unavailable) { + throw denied(); + } + } + + static Map parseActiveRecord(byte[] exact, String tokenHash) { + if (exact == null || exact.length == 0 || exact.length > MAX_RECORD_BYTES) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(exact)).toString(); + if (!Arrays.equals(exact, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(exact, OBJECT); + if (fields == null + || !fields.keySet().equals(FIELDS) + || !Integer.valueOf(1).equals(number(fields.get("schemaVersion"))) + || !Integer.valueOf(2).equals(number(fields.get("registryVersion"))) + || !tokenHash.equals(text(fields.get("tokenHash"))) + || !"firemud-account-service".equals(text(fields.get("issuer"))) + || !"control-ui".equals(text(fields.get("profile"))) + || !"control-ui".equals(text(fields.get("type"))) + || !"control-ui".equals(text(fields.get("audience"))) + || !"active".equals(text(fields.get("state"))) + || !KID.matcher(text(fields.get("kid"))).matches() + || !DECIMAL.matcher(text(fields.get("signerGeneration"))).matches() + || !DIGEST.matcher(text(fields.get("requestDigest"))).matches() + || !DIGEST.matcher(text(fields.get("originalSignerReceiptDigest"))).matches() + || !(fields.get("authorityTuple") instanceof Map) + || !(fields.get("membershipVersion") instanceof Map) + || !(fields.get("authoritySourceVersions") instanceof Map) + || !(fields.get("authEvidenceBundle") instanceof Map)) { + throw denied(); + } + requireUuid(fields.get("accountId")); + requireUuid(fields.get("jti")); + requireUuid(fields.get("operationId")); + requireUuid(fields.get("requestId")); + requirePositiveNumber(fields.get("iat")); + requirePositiveNumber(fields.get("nbf")); + requirePositiveNumber(fields.get("exp")); + requirePositiveNumber(fields.get("tokenGeneration")); + requirePositiveNumber(fields.get("issuanceFence")); + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + static long checkedExpiryMillis(Object encodedExpiry) { + try { + long exp = requirePositiveNumber(encodedExpiry); + // The committed control-ui profile uses the exact token expiry and zero cleanup margin. + return Math.multiplyExact(exp, 1000L); + } catch (ArithmeticException | IllegalArgumentException malformed) { + throw denied(); + } + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static long requirePositiveNumber(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + String encoded = number.toString(); + if (!DECIMAL.matcher(encoded).matches()) { + throw denied(); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static void requireUuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account Coordination reads cannot retain Account SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact Account active control-ui registry evidence unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..5b8a506b74 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.StatefulRedisConnection; + +/** Opens one private, dedicated, non-clustered Coordination connection for one Account read. */ +@FunctionalInterface +public interface AccountCoordinationPinnedConnectionProvider { + /** + * The provider must not return an ambient Spring connection, must disable automatic reconnect, + * and must retain one pinned physical Redis connection for the invocation. The caller checks the + * open/no-auto-reconnect contract and authenticates its ACL identity before reading data. + */ + StatefulRedisConnection openPinnedConnection(); +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java new file mode 100644 index 0000000000..3f2077f190 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -0,0 +1,704 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The Account-only Kubernetes adapter for the pre-created public {@code jwt-jwks} ConfigMap. Every + * write is a fixed-name, resourceVersion-guarded merge patch followed by exact readback. This class + * is intentionally not a lifecycle, readiness, or signer-promotion authority. + */ +public final class AccountJwtJwksConfigMapClient { + public static final String CONFIG_MAP_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_DATA_KEY = "jwt-generation.json"; + public static final int MAX_DESIRED_VALUE_BYTES = 768 * 1024; + private static final int MAX_CONFIG_MAP_DATA_KEYS = 128; + private static final int MAX_CONFIG_MAP_DATA_BYTES = 1024 * 1024; + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Set ACCOUNT_DATA_KEYS = Set.of(JWKS_DATA_KEY, GENERATION_DATA_KEY); + private static final Set PRIVATE_JWK_FIELDS = + Set.of("d", "p", "q", "dp", "dq", "qi", "oth", "k"); + private static final byte[] SELF_SUBJECT_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}" + .getBytes(StandardCharsets.UTF_8); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Supplier operationSupplier; + + /** Production constructor; API TLS and bearer handling remain inside the protected binding. */ + public AccountJwtJwksConfigMapClient(AccountJwtJwksApiBinding binding) { + AccountJwtJwksApiBinding requiredBinding = + Objects.requireNonNull(binding, "Account JWT JWKS API binding is required"); + this.operationSupplier = + () -> { + AccountJwtJwksApiBinding.ApiOperation operation = requiredBinding.beginOperation(); + return new ApiSession() { + @Override + public ParsedBinding binding() { + return operation.binding(); + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + return operation.send(call, body); + } + + @Override + public void close() { + operation.close(); + } + }; + }; + } + + /** Deterministic bounded transport seam for focused tests. */ + AccountJwtJwksConfigMapClient(Supplier operationSupplier) { + this.operationSupplier = + Objects.requireNonNull(operationSupplier, "API operation supplier is required"); + } + + /** + * Returns only the independently protected non-secret API/destination pins. Callers can compare + * these with Account's materializer binding before creating durable publication intent. + */ + public BindingIdentity identity() { + try (ApiSession operation = beginOperation()) { + return toIdentity(operation.binding()); + } + } + + /** + * Reads only the fixed pre-created public ConfigMap after checking Account API identity and both + * namespace incarnation pins. No list, create, delete, or Secret endpoint is available. + */ + public ConfigMapSnapshot observe() { + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + return readConfigMap(operation); + } + } + + /** + * Applies an exact owner-authored public data map using Kubernetes resourceVersion CAS. Only + * {@code jwks.json} and {@code jwt-generation.json} are accepted; unrelated data is preserved. An + * ambiguous write is successful only after a fresh exact-content readback on the same UID. + */ + public CasObservation publish(ConfigMapSnapshot expected, Map desiredPublicData) { + Objects.requireNonNull(expected, "expected ConfigMap snapshot is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(expected); + + try (ApiSession operation = beginOperation()) { + return publish(operation, expected, desired); + } + } + + /** + * Reconciles Account's exact active-marker transition from its durable prepublication RV. The + * freshly observed full snapshot preserves unrelated entries on a first write; an exact replay is + * accepted only when the live Account-owned data already matches and its RV advanced beyond the + * original prepublication fence. + */ + public CasObservation publishActiveProjection( + ConfigMapSnapshot observed, + String expectedPriorResourceVersion, + Map desiredPublicData) { + Objects.requireNonNull(observed, "fresh ConfigMap observation is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(observed); + if (expectedPriorResourceVersion == null + || !RESOURCE_VERSION.matcher(expectedPriorResourceVersion).matches()) { + throw new IllegalArgumentException("Active ConfigMap prior resourceVersion is malformed"); + } + + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(observed.uid()) + || !before.resourceVersion().equals(observed.resourceVersion()) + || !before.data().equals(observed.data())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + return observationWithPrior( + expectedPriorResourceVersion, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + + byte[] patch = createMergePatch(before, desired); + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(before, before, readback, desired); + return observationWithPrior(expectedPriorResourceVersion, readback, desired, Outcome.APPLIED); + } + } + + private CasObservation publish( + ApiSession operation, ConfigMapSnapshot expected, Map desired) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(expected.uid())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + return observation(expected, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + + byte[] patch = createMergePatch(expected, desired); + // Identity checks are repeated immediately before the only write call. + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(expected, before, readback, desired); + return observation(expected, readback, desired, Outcome.APPLIED); + } + + private CasObservation reconcileUnknownWrite( + ApiSession operation, + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + Map desired) { + try { + verifyEnvironment(operation); + ConfigMapSnapshot observed = readConfigMap(operation); + if (observed.uid().equals(expected.uid()) && sameAccountData(observed.data(), desired)) { + requirePreservedUnrelatedData(before, observed); + if (observed.resourceVersion().equals(expected.resourceVersion())) { + throw new UncertainOutcomeException(); + } + return observation(expected, observed, desired, Outcome.EXACT_REPLAY); + } + } catch (UncertainOutcomeException ex) { + throw ex; + } catch (RuntimeException ex) { + // The write outcome remains unknown when reconciliation itself is unavailable. + } + throw new UncertainOutcomeException(); + } + + private void requireExactPostcondition( + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + ConfigMapSnapshot readback, + Map desired) { + if (!readback.uid().equals(expected.uid()) + || readback.resourceVersion().equals(expected.resourceVersion()) + || !sameAccountData(readback.data(), desired)) { + throw new UncertainOutcomeException(); + } + requirePreservedUnrelatedData(before, readback); + } + + private static void requirePreservedUnrelatedData( + ConfigMapSnapshot before, ConfigMapSnapshot after) { + Map previous = unrelatedData(before.data()); + Map current = unrelatedData(after.data()); + if (!previous.equals(current)) { + throw new UncertainOutcomeException(); + } + } + + private static Map unrelatedData(Map data) { + Map unrelated = new LinkedHashMap<>(); + data.forEach( + (key, value) -> { + if (!ACCOUNT_DATA_KEYS.contains(key)) { + unrelated.put(key, value); + } + }); + return Map.copyOf(unrelated); + } + + private ConfigMapSnapshot readConfigMap(ApiSession operation) { + ApiResponse response = send(operation, ApiCall.READ_JWKS_CONFIG_MAP, null); + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + return parseConfigMap(response.body(), operation.binding()); + } + + private void verifyEnvironment(ApiSession operation) { + ParsedBinding binding = operation.binding(); + ApiResponse selfReview = + send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST); + if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201) + || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) { + throw new BindingRejectedException(); + } + verifyNamespace( + send(operation, ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + binding.expectedClusterIncarnationUid()); + verifyNamespace( + send(operation, ApiCall.READ_TARGET_NAMESPACE, null), + binding.namespace(), + binding.expectedNamespaceUid()); + } + + private void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (!isSuccess(response.statusCode())) { + if (response.statusCode() == 404) { + throw new BindingRejectedException(); + } + throw new ApiFailureException(response.statusCode()); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new BindingRejectedException(); + } + } + + private static String parseAuthenticatedUsername(byte[] bytes) { + JsonNode root = parseJson(bytes); + JsonNode status = root.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + String username = userInfo == null ? null : text(userInfo.get("username")); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(root.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(root.get("kind"))) + || username == null + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new BindingRejectedException(); + } + return username; + } + + private static ConfigMapSnapshot parseConfigMap(byte[] bytes, ParsedBinding binding) { + JsonNode root = parseJson(bytes); + JsonNode metadata = root.get("metadata"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"ConfigMap".equals(text(root.get("kind"))) + || metadata == null + || !CONFIG_MAP_NAME.equals(text(metadata.get("name"))) + || !binding.namespace().equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || Boolean.TRUE.equals(booleanValue(root.get("immutable"))) + || (root.has("binaryData") && !root.get("binaryData").isNull())) { + throw new ApiFailureException(0); + } + String uid = canonicalUid(text(metadata.get("uid"))); + String resourceVersion = text(metadata.get("resourceVersion")); + if (resourceVersion == null || !RESOURCE_VERSION.matcher(resourceVersion).matches()) { + throw new ApiFailureException(0); + } + Map data = parseData(root.get("data")); + return new ConfigMapSnapshot(uid, resourceVersion, data); + } + + private static Map parseData(JsonNode dataNode) { + if (dataNode == null || dataNode.isNull()) { + return Map.of(); + } + if (!dataNode.isObject() || dataNode.size() > MAX_CONFIG_MAP_DATA_KEYS) { + throw new ApiFailureException(0); + } + Map data = new LinkedHashMap<>(); + int totalBytes = 0; + for (Map.Entry entry : dataNode.properties()) { + JsonNode value = entry.getValue(); + if (!value.isTextual()) { + throw new ApiFailureException(0); + } + String text = value.asText(); + totalBytes += text.getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + data.put(entry.getKey(), text); + } + return Map.copyOf(data); + } + + private ApiSession beginOperation() { + try { + return Objects.requireNonNull(operationSupplier.get(), "API operation is unavailable"); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ApiSession operation, ApiCall call, byte[] body) { + try { + return operation.send(call, body); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + throw new ApiFailureException(0); + } + } + + private static BindingIdentity toIdentity(ParsedBinding binding) { + return new BindingIdentity( + binding.bindingDigest(), + binding.configRevision(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.apiServer().toString(), + binding.tlsServerName(), + binding.servingCaSha256(), + binding.expectedApiUsername()); + } + + private static Map validateDesiredPublicData(Map desired) { + if (desired == null || !desired.keySet().equals(ACCOUNT_DATA_KEYS)) { + throw new IllegalArgumentException("Account public JWKS data keys are invalid"); + } + Map copy = new LinkedHashMap<>(); + int total = 0; + for (String key : ACCOUNT_DATA_KEYS) { + String value = desired.get(key); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Account public JWKS data is incomplete"); + } + int length = value.getBytes(StandardCharsets.UTF_8).length; + if (length > MAX_DESIRED_VALUE_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + total += length; + copy.put(key, value); + } + if (total > MAX_CONFIG_MAP_DATA_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + validatePublicJwks(copy.get(JWKS_DATA_KEY)); + return Map.copyOf(copy); + } + + private static void validatePublicJwks(String jwks) { + JsonNode root = parseJson(jwks.getBytes(StandardCharsets.UTF_8)); + JsonNode keys = root.get("keys"); + if (!root.isObject() || root.size() != 1 || keys == null || !keys.isArray() || keys.isEmpty()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (JsonNode key : keys) { + if (!key.isObject()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (String privateField : PRIVATE_JWK_FIELDS) { + if (key.has(privateField)) { + throw new IllegalArgumentException("Account public JWKS contains private material"); + } + } + } + } + + private static byte[] createMergePatch(ConfigMapSnapshot expected, Map desired) { + Map metadata = new LinkedHashMap<>(); + metadata.put("uid", expected.uid()); + metadata.put("resourceVersion", expected.resourceVersion()); + Map patch = new LinkedHashMap<>(); + patch.put("metadata", metadata); + patch.put("data", desired); + try { + return STRICT_JSON.writeValueAsBytes(patch); + } catch (Exception ex) { + throw new IllegalStateException("Account public JWKS patch could not be encoded"); + } + } + + private static boolean sameAccountData(Map current, Map desired) { + return desired.get(JWKS_DATA_KEY).equals(current.get(JWKS_DATA_KEY)) + && desired.get(GENERATION_DATA_KEY).equals(current.get(GENERATION_DATA_KEY)); + } + + private static CasObservation observation( + ConfigMapSnapshot expected, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + expected.resourceVersion(), + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasObservation observationWithPrior( + String priorResourceVersion, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + priorResourceVersion, + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasConflictException conflict(ConfigMapSnapshot observed) { + return new CasConflictException(observed.uid(), observed.resourceVersion()); + } + + private static void requireSnapshotIdentity(ConfigMapSnapshot snapshot) { + if (!validUid(snapshot.uid()) + || snapshot.resourceVersion() == null + || !RESOURCE_VERSION.matcher(snapshot.resourceVersion()).matches()) { + throw new IllegalArgumentException("Expected ConfigMap snapshot identity is malformed"); + } + } + + private static boolean isSuccess(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject()) { + throw new ApiFailureException(0); + } + return root; + } catch (CharacterCodingException | RuntimeException ex) { + throw new ApiFailureException(0); + } + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String canonicalUid(String value) { + if (!validUid(value)) { + throw new ApiFailureException(0); + } + return value; + } + + private static boolean validUid(String value) { + return value != null + && UID.matcher(value).matches() + && !"00000000-0000-0000-0000-000000000000".equals(value); + } + + interface ApiSession extends AutoCloseable { + ParsedBinding binding(); + + ApiResponse send(ApiCall call, byte[] body); + + @Override + void close(); + } + + public record BindingIdentity( + String bindingDigest, + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiServerUrl, + String tlsServerName, + String servingCaSha256, + String expectedApiUsername) {} + + public record ConfigMapSnapshot(String uid, String resourceVersion, Map data) { + public ConfigMapSnapshot { + data = data == null ? Map.of() : Map.copyOf(data); + } + } + + public record CasObservation( + String uid, + String priorResourceVersion, + String resourceVersion, + Map publishedData, + Map readbackData, + Outcome outcome) { + public CasObservation { + publishedData = Map.copyOf(publishedData); + readbackData = Map.copyOf(readbackData); + } + } + + public enum Outcome { + APPLIED, + EXACT_REPLAY + } + + public static class ResourceMissingException extends RuntimeException { + public ResourceMissingException() { + super("Pre-created Account public JWKS ConfigMap is unavailable"); + } + } + + public static class CasConflictException extends RuntimeException { + private final String observedUid; + private final String observedResourceVersion; + + public CasConflictException(String observedUid, String observedResourceVersion) { + super("Account public JWKS ConfigMap compare-and-set conflict"); + this.observedUid = observedUid; + this.observedResourceVersion = observedResourceVersion; + } + + public String observedUid() { + return observedUid; + } + + public String observedResourceVersion() { + return observedResourceVersion; + } + } + + public static class UncertainOutcomeException extends RuntimeException { + public UncertainOutcomeException() { + super("Account public JWKS ConfigMap write outcome is uncertain"); + } + } + + public static class ApiFailureException extends RuntimeException { + private final int statusCode; + + public ApiFailureException(int statusCode) { + super("Account public JWKS Kubernetes API request failed"); + this.statusCode = statusCode; + } + + public int statusCode() { + return statusCode; + } + } + + public static class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account public JWKS API binding or identity was rejected"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java new file mode 100644 index 0000000000..4742f95fed --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -0,0 +1,761 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned authenticated read adapter for the current public JWKS publication. + * + *

The cache pin is derived from Account's root-protected Kubernetes API binding and exact + * Account-owned publication evidence. The first receipt-backed PREPUBLISHED key can be served to + * readiness probes before a signer is committed, but is never represented as active authority. + * During ordinary prepublication of a next key, the prior committed key remains the only active + * signer while the exact new public set may be served for validation overlap. PREPARED and + * unexplained resource changes deny. This adapter exposes only public JWKS bytes and grants no + * signing, registry, readiness, or admission authority. + */ +public final class AccountJwtJwksTrustedSource + implements AccountPublicJwksCache.TrustedPublicJwksSource { + private static final int MAX_JWKS_BYTES = 256 * 1024; + private static final int MAX_MARKER_BYTES = 16 * 1024; + private static final String ACCOUNT_SERVICE_USERNAME_PREFIX = "system:serviceaccount:"; + private static final String ACCOUNT_SERVICE_NAME = "account-service"; + private static final int MAX_KEYS = 64; + private static final java.util.Set JWKS_FIELDS = java.util.Set.of("keys"); + private static final java.util.Set JWK_FIELDS = + java.util.Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final TransactionTemplate accountTransaction; + private final Object pinMonitor = new Object(); + + private volatile TrustedPin trustedPin; + + /** Constructs an inactive adapter over Account's real protected API and owner-recorded state. */ + public AccountJwtJwksTrustedSource( + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + PlatformTransactionManager transactionManager) { + this.configMapClient = + Objects.requireNonNull(configMapClient, "Account ConfigMap client is required"); + this.materializerTrustBinding = + Objects.requireNonNull(materializerTrustBinding, "Protected Account trust is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "Account publication repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.accountTransaction.setReadOnly(false); + } + + /** + * Establishes the immutable cache pin from a coherent, protected Account read. A cache owner + * obtains its expected source identity here; it is not accepted as caller-supplied evidence. + */ + public SourceIdentity sourceIdentity() { + TrustedPin current = trustedPin; + if (current != null) { + return current.sourceIdentity(); + } + synchronized (pinMonitor) { + current = trustedPin; + if (current == null) { + VerifiedSource verified = readVerifiedSource(); + current = verified.pin(); + trustedPin = current; + } + } + return current.sourceIdentity(); + } + + /** + * Derives one key's RFC 7638 fingerprint from a snapshot already loaded through this trusted + * source. It compares the immutable pin and grants no signer, registry, or token authority. + */ + static Optional publicKeyFingerprint( + PublicJwksSnapshot snapshot, SourceIdentity expectedSourceIdentity, String kid) { + if (snapshot == null + || expectedSourceIdentity == null + || !expectedSourceIdentity.equals(snapshot.sourceIdentity()) + || kid == null + || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw rejected(); + } + Map fingerprints = + publicKeyFingerprints(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)); + return Optional.ofNullable(fingerprints.get(kid)); + } + + /** + * Loads one exact public JWKS snapshot after checking Account trust and receipt readback twice. + */ + @Override + public PublicJwksSnapshot load() { + TrustedPin expected = trustedPin; + if (expected == null) { + throw rejected(); + } + VerifiedSource verified = readVerifiedSource(); + if (!expected.equals(verified.pin())) { + throw rejected(); + } + return new PublicJwksSnapshot(expected.sourceIdentity(), verified.jwksBytes()); + } + + private VerifiedSource readVerifiedSource() { + Binding materializerBefore = currentMaterializerBinding(); + BindingIdentity apiBefore = currentApiIdentity(); + requireBindingsAgree(materializerBefore, apiBefore); + TrustedPin alreadyPinned = trustedPin; + if (alreadyPinned != null + && (!alreadyPinned.materializerBinding().equals(materializerBefore) + || !alreadyPinned.apiIdentity().equals(apiBefore))) { + throw rejected(); + } + + OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore); + SourceIdentity pinnedIdentity = + sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); + if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) { + throw rejected(); + } + + ConfigMapSnapshot live; + try { + live = configMapClient.observe(); + } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + throw unavailable(); + } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + if (isTemporaryApiFailure(failure.statusCode())) { + throw unavailable(); + } + throw rejected(); + } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) { + throw rejected(); + } catch (RuntimeException unexpected) { + throw rejected(); + } + + Binding materializerAfter = currentMaterializerBinding(); + BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw rejected(); + } + + OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter); + if (!ownerBefore.equals(ownerAfter)) { + // A concurrent Account lifecycle/publication change is not a coherent source snapshot. + throw unavailable(); + } + requireExactReadback(ownerAfter.projection(), live); + + byte[] jwks = + live.data() + .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) + .getBytes(StandardCharsets.UTF_8); + if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) { + throw rejected(); + } + TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity); + return new VerifiedSource(pin, jwks); + } + + private Binding currentMaterializerBinding() { + return materializerTrustBinding.current().orElseThrow(AccountJwtJwksTrustedSource::rejected); + } + + private BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException rejectedBinding) { + throw rejected(); + } + } + + private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw rejected(); + } + try { + OwnerProjection result = + accountTransaction.execute( + status -> { + DesiredState enrolled = + desiredStateRepository + .readEnrollmentState(binding.accountBinding()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { + return initialPrepublicationProjection(enrolled, binding, api); + } + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trustFence(binding), + api.bindingDigest(), + api.configRevision()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + ActiveSigner currentActive = + new ActiveSigner( + committed.promotion().targetGeneration(), + committed.promotion().targetKid()); + PublishedProjection projection = committedProjection(committed); + if (committed.desiredState().generationOperationId().isEmpty()) { + return new OwnerProjection(committed, projection); + } + + var request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { + return new OwnerProjection(committed, projection); + } + Optional currentPublication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (currentPublication.isEmpty() + || currentPublication.orElseThrow().receipt().isEmpty()) { + return new OwnerProjection(committed, projection); + } + PublicationEvidence evidence = currentPublication.orElseThrow(); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(); + if (!intent.operationId().equals(request.operationId()) + || !intent.operationDigest().equals(request.operationDigest()) + || !intent.generationRequestDigest().equals(request.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) + || !intent.targetGeneration().equals(request.targetGeneration()) + || !intent.targetKid().equals(request.targetKid()) + || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(Optional.of(currentActive)) + || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) + || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + requireRetainedPublicKeySet(committed, intent); + return new OwnerProjection( + committed, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + }); + if (result == null) { + throw unavailable(); + } + return result; + } catch (RuntimeException ownerStateUnavailable) { + if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { + throw unavailable; + } + if (ownerStateUnavailable instanceof IllegalStateException + && ownerStateUnavailable.getMessage() != null + && ownerStateUnavailable.getMessage().contains("Account trusted public JWKS source")) { + throw ownerStateUnavailable; + } + throw rejected(); + } + } + + /** + * The first exact Account-receipted PREPUBLISHED set is visible to validator probes before any + * signer is committed. It is never represented as an active signer and remains unavailable during + * PREPARED or after any active fence appears. + */ + private OwnerProjection initialPrepublicationProjection( + DesiredState enrolled, Binding binding, BindingIdentity api) { + if (!enrolled.binding().equals(binding.accountBinding()) + || enrolled.preparedOperationId().isPresent() + || enrolled.generationOperationId().isEmpty() + || enrolled.enrollmentIdentity().isEmpty()) { + throw rejected(); + } + EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow(); + if (!enrollment.expectedClusterIncarnationUid().equals(binding.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(binding.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(binding.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(binding.configRevision()) + || !enrollment.apiBindingDigest().equals(api.bindingDigest()) + || !enrollment.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.expectedActive().isEmpty() + || !request.expectedPublishedActive().isEmpty() + || !enrolled.generationOperationId().equals(Optional.of(request.operationId())) + || !request.binding().equals(binding.accountBinding()) + || !request.trustFence().equals(trustFence(binding)) + || !result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || request.desiredStateVersion() != result.desiredStateVersion() + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationRequestDigest().equals(result.generationRequestDigest()) + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !"RS256".equals(result.targetAlgorithm())) { + throw rejected(); + } + + PublicationEvidence evidence = + publicationRepository + .readCurrentPublication(binding.accountBinding(), trustFence(binding)) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.expectedDurableActive().isEmpty() + || !intent.expectedPublishedActive().isEmpty() + || !intent.configMapUid().equals(enrollment.publicConfigMapUid()) + || !receipt.configMapUid().equals(enrollment.publicConfigMapUid()) + || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest()) + || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw rejected(); + } + Map publicKeys = publicKeyFingerprints(intent.jwksJson()); + if (publicKeys.size() != 1 + || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) { + throw rejected(); + } + requireInitialPrepublicationMarker(intent, result, binding, api); + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + } + + private static void requireInitialPrepublicationMarker( + PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) { + try { + JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson()); + JsonNode markerBinding = marker == null ? null : marker.get("binding"); + JsonNode publicConfigMap = marker == null ? null : marker.get("publicConfigMap"); + JsonNode pending = marker == null ? null : marker.get("pending"); + JsonNode durable = marker == null ? null : marker.get("expectedDurableActive"); + JsonNode published = marker == null ? null : marker.get("expectedPublishedActive"); + if (marker == null + || !marker.isObject() + || !hasExactFields( + marker, + java.util.Set.of( + "schemaVersion", + "phase", + "operationId", + "operationDigest", + "generationRequestDigest", + "generationReceiptDigest", + "binding", + "publicConfigMap", + "expectedDurableActive", + "expectedPublishedActive", + "pending")) + || !marker.get("schemaVersion").isIntegralNumber() + || marker.get("schemaVersion").intValue() != 1 + || !"PREPUBLISHED".equals(requiredText(marker, "phase")) + || !intent.operationId().toString().equals(requiredText(marker, "operationId")) + || !intent.operationDigest().equals(requiredText(marker, "operationDigest")) + || !intent + .generationRequestDigest() + .equals(requiredText(marker, "generationRequestDigest")) + || !intent + .generationReceiptDigest() + .equals(requiredText(marker, "generationReceiptDigest")) + || !hasExactFields( + markerBinding, + java.util.Set.of( + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision")) + || !binding.environmentId().equals(requiredText(markerBinding, "environmentId")) + || !binding.clusterId().equals(requiredText(markerBinding, "clusterId")) + || !binding.namespace().equals(requiredText(markerBinding, "namespace")) + || !binding + .expectedClusterIncarnationUid() + .equals(requiredText(markerBinding, "expectedClusterIncarnationUid")) + || !binding + .expectedNamespaceUid() + .equals(requiredText(markerBinding, "expectedNamespaceUid")) + || !binding.bindingDigest().equals(requiredText(markerBinding, "trustBindingDigest")) + || !binding.configRevision().equals(requiredText(markerBinding, "trustConfigRevision")) + || !api.bindingDigest().equals(requiredText(markerBinding, "apiBindingDigest")) + || !api.configRevision().equals(requiredText(markerBinding, "apiConfigRevision")) + || !hasExactFields(publicConfigMap, java.util.Set.of("name")) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals( + requiredText(publicConfigMap, "name")) + || !hasExactFields( + pending, java.util.Set.of("generation", "kid", "algorithm", "publicKeyFingerprint")) + || !result.targetGeneration().equals(requiredText(pending, "generation")) + || !result.targetKid().equals(requiredText(pending, "kid")) + || !"RS256".equals(requiredText(pending, "algorithm")) + || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) + || !inactiveMarker(durable) + || !inactiveMarker(published)) { + throw rejected(); + } + } catch (RuntimeException malformed) { + throw rejected(); + } + } + + private static boolean inactiveMarker(JsonNode marker) { + return hasExactFields(marker, java.util.Set.of("present")) + && marker.get("present").isBoolean() + && !marker.get("present").booleanValue(); + } + + private static void requireBindingsAgree(Binding materializer, BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || api.bindingDigest() == null + || api.configRevision() == null + || api.expectedApiUsername() == null + || !api.expectedApiUsername() + .equals( + ACCOUNT_SERVICE_USERNAME_PREFIX + + materializer.namespace() + + ":" + + ACCOUNT_SERVICE_NAME)) { + throw rejected(); + } + URI endpoint; + try { + endpoint = URI.create(api.apiServerUrl()); + } catch (RuntimeException malformedEndpoint) { + throw rejected(); + } + if (!"https".equalsIgnoreCase(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() <= 0 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null + && !endpoint.getRawPath().isEmpty() + && !"/".equals(endpoint.getRawPath())) + || api.tlsServerName() == null + || !endpoint.getHost().equalsIgnoreCase(api.tlsServerName()) + || api.servingCaSha256() == null) { + throw rejected(); + } + } + + private static void requirePublicationBinding( + PublicationEvidence evidence, Binding materializer, BindingIdentity api) { + PrepublicationIntent intent = evidence.intent(); + if (!intent.binding().equals(materializer.accountBinding()) + || !intent.trustFence().equals(trustFence(materializer)) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(intent.configMapName()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision()) + || !AccountJwtJwksPublicationRepository.publicDataDigest( + intent.jwksJson(), intent.generationMarkerJson()) + .equals(intent.publicDataDigest())) { + throw rejected(); + } + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt != null + && (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(materializer.accountBinding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()))) { + throw rejected(); + } + } + + private static PublishedProjection committedProjection(CommittedSignerEvidence committed) { + PromotionOperationEvidence promotion = committed.promotion(); + var receipt = committed.publicReceipt(); + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); + if (!promotion.publicConfigMapUid().equals(receipt.configMapUid()) + || !promotion + .activeJwksObservedResourceVersion() + .orElseThrow() + .equals(receipt.observedResourceVersion()) + || !promotion.activeJwksPublicDataDigest().orElseThrow().equals(dataDigest) + || !receipt.publicDataDigest().equals(dataDigest)) { + throw rejected(); + } + return new PublishedProjection( + receipt.configMapUid(), + receipt.observedResourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + dataDigest); + } + + private static void requireRetainedPublicKeySet( + CommittedSignerEvidence committed, PrepublicationIntent intent) { + Map previousKeys = + publicKeyFingerprints(committed.promotion().expectedPublicJwksJson()); + Map currentKeys = publicKeyFingerprints(intent.jwksJson()); + if (previousKeys.isEmpty() || currentKeys.size() < previousKeys.size()) { + throw rejected(); + } + if (new BigInteger(intent.targetGeneration()) + .compareTo(new BigInteger(committed.promotion().targetGeneration())) + <= 0) { + throw rejected(); + } + for (Map.Entry previous : previousKeys.entrySet()) { + if (!previous.getValue().equals(currentKeys.get(previous.getKey()))) { + throw rejected(); + } + } + if (!intent.publicKeyFingerprint().equals(currentKeys.get(intent.targetKid())) + || !committed + .promotion() + .targetPublicKeyFingerprint() + .equals(currentKeys.get(committed.promotion().targetKid()))) { + throw rejected(); + } + } + + private static Map publicKeyFingerprints(String jwksJson) { + try { + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > MAX_JWKS_BYTES) { + throw new IllegalArgumentException(); + } + JsonNode root = STRICT_JSON.readTree(jwksJson); + if (root == null || !root.isObject() || !hasExactFields(root, JWKS_FIELDS)) { + throw new IllegalArgumentException(); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.isEmpty() || keys.size() > MAX_KEYS) { + throw new IllegalArgumentException(); + } + Map fingerprints = new LinkedHashMap<>(); + for (JsonNode key : keys) { + if (key == null || !key.isObject() || !hasExactFields(key, JWK_FIELDS)) { + throw new IllegalArgumentException(); + } + String kty = requiredText(key, "kty"); + String use = requiredText(key, "use"); + String alg = requiredText(key, "alg"); + String kid = requiredText(key, "kid"); + String modulus = requiredText(key, "n"); + String exponent = requiredText(key, "e"); + JsonNode keyOps = key.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException(); + } + String preimage = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + STRICT_JSON.writeValueAsString( + Map.of("e", exponent, "kty", kty, "n", modulus))), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + if (fingerprints.putIfAbsent(kid, fingerprint) != null) { + throw new IllegalArgumentException(); + } + } + return Map.copyOf(fingerprints); + } catch (IOException | NoSuchAlgorithmException | RuntimeException malformed) { + throw rejected(); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException(); + } + return value.textValue(); + } + + private static boolean hasExactFields(JsonNode object, java.util.Set expected) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + return false; + } + for (Map.Entry property : object.properties()) { + if (!expected.contains(property.getKey())) { + return false; + } + } + return true; + } + + private static void requireExactReadback(PublishedProjection projection, ConfigMapSnapshot live) { + String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + if (!projection.configMapUid().equals(live.uid()) + || !projection.resourceVersion().equals(live.resourceVersion()) + || !projection.jwksJson().equals(jwks) + || !projection.markerJson().equals(marker) + || marker == null + || marker.getBytes(StandardCharsets.UTF_8).length > MAX_MARKER_BYTES + || !AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker) + .equals(projection.publicDataDigest())) { + throw rejected(); + } + } + + private static SourceIdentity sourceIdentity( + Binding materializer, BindingIdentity api, String configMapUid) { + try { + return new SourceIdentity( + materializer.environmentId(), + materializer.clusterId(), + materializer.expectedClusterIncarnationUid(), + materializer.namespace(), + materializer.expectedNamespaceUid(), + configMapUid, + api.configRevision(), + api.apiServerUrl(), + api.servingCaSha256()); + } catch (RuntimeException invalidIdentity) { + throw rejected(); + } + } + + private void requireUnchangedProtectedTrust(Binding expected, BindingIdentity expectedApi) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expected.equals(currentMaterializer) || !expectedApi.equals(currentApi)) { + throw rejected(); + } + } + + private static boolean isTemporaryApiFailure(int statusCode) { + return statusCode == 0 || statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + private static IllegalStateException rejected() { + return new IllegalStateException("Account trusted public JWKS source was rejected"); + } + + private record TrustedPin( + Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {} + + private record OwnerProjection( + CommittedSignerEvidence committedSigner, PublishedProjection projection) {} + + private record PublishedProjection( + String configMapUid, + String resourceVersion, + String jwksJson, + String markerJson, + String publicDataDigest) {} + + private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java new file mode 100644 index 0000000000..3344965501 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** Closed, bounded selector for an authenticated read of one current V2 readiness entry. */ +public record AccountJwtReadinessProbeOwnerSelector( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + int registryVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectedOutcome, + UUID jti, + long entryVersion, + String targetGeneration, + String targetKid, + Optional expectedActive, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + long planExpiresAtEpochSecond, + String compactTokenSha256, + LocalIdentity localIdentity) { + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + + public AccountJwtReadinessProbeOwnerSelector { + Objects.requireNonNull(rotationOperationId, "operation ID is required"); + if (rotationOperationId.version() != 4 || rotationOperationId.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness operation UUIDv4 is required"); + } + requireDigest(operationDigest, "operation digest"); + requireDigest(planDigest, "plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || registryVersion != 1 + || entryVersion <= 0L) { + throw new IllegalArgumentException("Current V2 readiness coordinates are required"); + } + requireId(validatorId, "validator ID"); + requireProfile(tokenProfile); + requireProfile(audience); + Objects.requireNonNull(probeKind, "probe kind is required"); + Objects.requireNonNull(expectedOutcome, "expected outcome is required"); + Objects.requireNonNull(jti, "probe JTI is required"); + if (jti.version() != 4 || jti.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness JTI is required"); + } + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive, "active fence state is required"); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || planExpiresAtEpochSecond <= 0L + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness probe time bounds are malformed"); + } + requireDigest(compactTokenSha256, "compact token digest"); + Objects.requireNonNull(localIdentity, "protected local identity is required"); + } + + public record LocalIdentity( + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String directPodEndpoint, + String canonicalServiceUri, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + String sourceInventoryRevision, + String sourceInventoryDigest, + String serverLeafSpkiSha256) { + public LocalIdentity { + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "deployment UID"); + requireCanonicalUuid(podUid, "Pod UID"); + if (!net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding + .canonicalPodIp(podIp) + .equals(podIp)) { + throw new IllegalArgumentException("Pod IP is not canonical"); + } + requireText(directPodEndpoint, 256, "direct Pod endpoint"); + requireText(canonicalServiceUri, 256, "canonical service URI"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be digest-pinned"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + if (sourceInventoryRevision == null || !REVISION.matcher(sourceInventoryRevision).matches()) { + throw new IllegalArgumentException("Receiver source inventory revision is malformed"); + } + requireDigest(sourceInventoryDigest, "receiver source inventory digest"); + requireDigest(serverLeafSpkiSha256, "receiver TLS SPKI digest"); + URI endpoint = URI.create(directPodEndpoint); + if (!endpoint.toString().equals(directPodEndpoint) + || !canonicalServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException("Receiver endpoint or service identity is malformed"); + } + } + } + + private static void requireCanonicalUuid(String value, String label) { + if (value == null + || !value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(label + " is not canonical"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireId(String value, String label) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireProfile(String value) { + if (value == null || !PROFILE.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness profile or audience is malformed"); + } + } + + private static void requireKid(String value) { + if (value == null || !KID.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target key ID is malformed"); + } + } + + private static void requireGeneration(String value) { + if (value == null || !GENERATION.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target generation is malformed"); + } + } + + private static void requireText(String value, int maximum, String label) { + if (value == null + || value.isBlank() + || value.length() > maximum + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java new file mode 100644 index 0000000000..88acaea9a6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java @@ -0,0 +1,593 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +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.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** + * Account-owned internal invocation boundary for one exact validator Pod and one exact probe. + * + *

The production implementation must route to the observed Pod endpoint, verify the TLS peer + * against its protected Pod-specific pin while retaining the canonical service SAN, and return an + * {@link AuthenticatedAcceptance} only after validating the receiver's production-verifier result + * and local Pod identity. No RPC request or harness DTO is an implementation of this port. + */ +public abstract class AccountJwtReadinessReceiverInvocationPort { + private static final Pattern UUID_V4 = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern UUID_CANONICAL = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + /** Invokes one Pod; implementations must fail closed if any target binding is unavailable. */ + public abstract AuthenticatedAcceptance invoke(Invocation invocation); + + /** Availability guard called before one-shot signing or delivery is durably claimed. */ + public abstract void requireAvailable(); + + /** No remote receiver or Pod-bound transport identity is currently composed. */ + public static AccountJwtReadinessReceiverInvocationPort defaultDenied() { + return new AccountJwtReadinessReceiverInvocationPort() { + @Override + public AuthenticatedAcceptance invoke(Invocation invocation) { + throw new ReceiverUnavailableException(); + } + + @Override + public void requireAvailable() { + throw new ReceiverUnavailableException(); + } + }; + } + + /** Owner-package factory for a response already authenticated by the real Pod-bound client. */ + static AuthenticatedAcceptance authenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + return new AuthenticatedAcceptance( + podUid, + actualPodEndpoint, + image, + verifierConfigSha256, + actualServiceUri, + actualPeerSpkiSha256, + jti, + compactTokenSha256, + verifiedKid, + result, + observedAtEpochSecond); + } + + /** Exact, non-secret Pod target derived by Account from one protected inventory snapshot. */ + public record PodTarget( + String inventorySnapshotDigest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + ProbeExpectation expectation, + Optional exactPodEndpoint, + Optional canonicalServiceUri, + Optional podLeafSpkiSha256) { + public PodTarget { + requireDigest(inventorySnapshotDigest, "inventory snapshot digest"); + requireIdentity(environmentId, "environment ID"); + requireCluster(clusterId); + requireCanonicalUuid(clusterIncarnationUid, "cluster incarnation UID"); + requireIdentity(namespace, "Kubernetes namespace"); + requireCanonicalUuid(namespaceUid, "namespace UID"); + requireRevision(apiBindingRevision, "Kubernetes API binding revision"); + requireDigest(apiBindingDigest, "Kubernetes API binding digest"); + requireRevision(inventoryBindingRevision, "inventory binding revision"); + requireDigest(inventoryBindingDigest, "inventory binding digest"); + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "validator Deployment UID"); + requireCanonicalUuid(podUid, "validator Pod UID"); + if (!AccountJwtValidatorInventoryBinding.canonicalPodIp(podIp).equals(podIp)) { + throw new IllegalArgumentException("Protected validator Pod IP is not canonical"); + } + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be pinned by digest"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + Objects.requireNonNull(expectation, "probe expectation is required"); + exactPodEndpoint = Objects.requireNonNull(exactPodEndpoint); + canonicalServiceUri = Objects.requireNonNull(canonicalServiceUri); + podLeafSpkiSha256 = Objects.requireNonNull(podLeafSpkiSha256); + exactPodEndpoint.ifPresent(endpoint -> requirePodEndpoint(endpoint, podIp)); + canonicalServiceUri.ifPresent(AccountJwtReadinessReceiverInvocationPort::requireServiceUri); + podLeafSpkiSha256.ifPresent(value -> requireDigest(value, "Pod TLS leaf SPKI digest")); + } + + /** Missing addressing or a Pod-specific peer pin makes this target non-invocable. */ + public void requireRoutablePodIdentity() { + if (exactPodEndpoint.isEmpty() + || canonicalServiceUri.isEmpty() + || podLeafSpkiSha256.isEmpty()) { + throw new ReceiverUnavailableException(); + } + } + } + + /** One exact logical registry probe, including transient signed bytes but no signer authority. */ + public static final class Invocation { + private final UUID rotationOperationId; + private final String operationDigest; + private final String planDigest; + private final int planVersion; + private final long planExpiresAtEpochSecond; + private final String validatorId; + private final String tokenProfile; + private final String audience; + private final ProbeKind probeKind; + private final ProbeExpectation expectation; + private final int registryVersion; + private final long sourceEntryVersion; + private final UUID jti; + private final String compactJwt; + private final String compactTokenSha256; + private final String targetGeneration; + private final String targetKid; + private final Optional expectedActiveGeneration; + private final Optional expectedActiveKid; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final PodTarget target; + + Invocation( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + long planExpiresAtEpochSecond, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectation, + int registryVersion, + long sourceEntryVersion, + UUID jti, + String compactJwt, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + PodTarget target) { + this.rotationOperationId = Objects.requireNonNull(rotationOperationId); + requireUuid(rotationOperationId.toString(), "rotation operation ID"); + requireDigest(operationDigest, "generation operation digest"); + requireDigest(planDigest, "readiness plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || planExpiresAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Exact V2 readiness plan coordinates are required"); + } + requireId(validatorId, "validator ID"); + if (tokenProfile == null || !tokenProfile.matches("[a-z][a-z0-9-]{0,127}")) { + throw new IllegalArgumentException("Token profile is malformed"); + } + if (audience == null || !audience.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("Token audience is malformed"); + } + this.operationDigest = operationDigest; + this.planDigest = planDigest; + this.planVersion = planVersion; + this.planExpiresAtEpochSecond = planExpiresAtEpochSecond; + this.validatorId = validatorId; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.probeKind = Objects.requireNonNull(probeKind); + this.expectation = Objects.requireNonNull(expectation); + if (registryVersion != 1 || sourceEntryVersion <= 0L) { + throw new IllegalArgumentException("Readiness entry version is malformed"); + } + this.registryVersion = registryVersion; + this.sourceEntryVersion = sourceEntryVersion; + this.jti = Objects.requireNonNull(jti); + requireUuid(jti.toString(), "probe JTI"); + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16 * 1024 + || !compactJwt.matches("[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+")) { + throw new IllegalArgumentException("Compact readiness token is malformed"); + } + requireDigest(compactTokenSha256, "compact readiness token digest"); + if (!compactTokenSha256.equals(sha256(compactJwt))) { + throw new IllegalArgumentException("Compact readiness token digest does not match bytes"); + } + this.compactJwt = compactJwt; + this.compactTokenSha256 = compactTokenSha256; + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Target key ID is malformed"); + } + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.expectedActiveGeneration = Objects.requireNonNull(expectedActiveGeneration); + this.expectedActiveKid = Objects.requireNonNull(expectedActiveKid); + if (expectedActiveGeneration.isPresent() != expectedActiveKid.isPresent()) { + throw new IllegalArgumentException("Expected active signer fence is partial"); + } + this.expectedActiveGeneration.ifPresent( + value -> { + if (!value.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Expected active generation is malformed"); + } + }); + this.expectedActiveKid.ifPresent( + value -> { + if (!value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Expected active key ID is malformed"); + } + }); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness token lifetime is malformed"); + } + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.target = Objects.requireNonNull(target); + if (!validatorId.equals(target.validatorId())) { + throw new IllegalArgumentException("Readiness probe and Pod validator differ"); + } + } + + public UUID rotationOperationId() { + return rotationOperationId; + } + + public String operationDigest() { + return operationDigest; + } + + public String planDigest() { + return planDigest; + } + + public int planVersion() { + return planVersion; + } + + public long planExpiresAtEpochSecond() { + return planExpiresAtEpochSecond; + } + + public String validatorId() { + return validatorId; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public ProbeExpectation expectation() { + return expectation; + } + + public int registryVersion() { + return registryVersion; + } + + public long sourceEntryVersion() { + return sourceEntryVersion; + } + + public UUID jti() { + return jti; + } + + public String compactJwt() { + return compactJwt; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public Optional expectedActiveGeneration() { + return expectedActiveGeneration; + } + + public Optional expectedActiveKid() { + return expectedActiveKid; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public PodTarget target() { + return target; + } + + @Override + public String toString() { + return "AccountJwtReadinessReceiverInvocation[rotationOperationId=" + + rotationOperationId + + ", validatorId=" + + validatorId + + ", podUid=" + + target.podUid() + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public enum ProbeExpectation { + ACCEPT, + INAPPLICABLE_REJECT + } + + /** + * Internal result established by the Account-owned receiver client after mTLS and response + * identity checks. Its package-private constructor is not available to an RPC adapter/harness. + */ + public static final class AuthenticatedAcceptance { + private final String podUid; + private final String actualPodEndpoint; + private final String image; + private final String verifierConfigSha256; + private final String actualServiceUri; + private final String actualPeerSpkiSha256; + private final UUID jti; + private final String compactTokenSha256; + private final String verifiedKid; + private final ProbeExpectation result; + private final long observedAtEpochSecond; + + private AuthenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + requireCanonicalUuid(podUid, "receiver-reported local Pod UID"); + requirePodEndpointShape(actualPodEndpoint); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Receiver image is not pinned by digest"); + } + requireDigest(verifierConfigSha256, "receiver verifier configuration digest"); + requireServiceUri(actualServiceUri); + requireDigest(actualPeerSpkiSha256, "authenticated peer SPKI digest"); + Objects.requireNonNull(jti); + requireUuid(jti.toString(), "receiver probe JTI"); + requireDigest(compactTokenSha256, "receiver compact token digest"); + if (verifiedKid == null || !verifiedKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Receiver verified key ID is malformed"); + } + this.result = Objects.requireNonNull(result); + if (observedAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Receiver observation time is malformed"); + } + this.podUid = podUid; + this.actualPodEndpoint = actualPodEndpoint; + this.image = image; + this.verifierConfigSha256 = verifierConfigSha256; + this.actualServiceUri = actualServiceUri; + this.actualPeerSpkiSha256 = actualPeerSpkiSha256; + this.jti = jti; + this.compactTokenSha256 = compactTokenSha256; + this.verifiedKid = verifiedKid; + this.observedAtEpochSecond = observedAtEpochSecond; + } + + public String podUid() { + return podUid; + } + + public String actualPodEndpoint() { + return actualPodEndpoint; + } + + public String image() { + return image; + } + + public String verifierConfigSha256() { + return verifierConfigSha256; + } + + public String actualServiceUri() { + return actualServiceUri; + } + + public String actualPeerSpkiSha256() { + return actualPeerSpkiSha256; + } + + public UUID jti() { + return jti; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String verifiedKid() { + return verifiedKid; + } + + public ProbeExpectation result() { + return result; + } + + public long observedAtEpochSecond() { + return observedAtEpochSecond; + } + + @Override + public String toString() { + return "AccountJwtReadinessAuthenticatedAcceptance[podUid=" + + podUid + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public static final class ReceiverUnavailableException extends IllegalStateException { + public ReceiverUnavailableException() { + super("Account JWT readiness receiver transport is unavailable"); + } + } + + private static void requirePodEndpoint(URI endpoint, String podIp) { + String endpointHost = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty()) + || !endpoint.toString().equals("grpcs://" + endpointHost + ":" + endpoint.getPort())) { + throw new IllegalArgumentException("Exact Pod endpoint is malformed"); + } + } + + private static void requirePodEndpointShape(String value) { + try { + URI endpoint = URI.create(value); + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty())) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed"); + } + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed", failure); + } + } + + private static void requireServiceUri(String value) { + if (value == null || !SERVICE_URI.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical validator service SAN is malformed"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireUuid(String value, String name) { + if (value == null || !UUID_V4.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCanonicalUuid(String value, String name) { + if (value == null || !UUID_CANONICAL.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireId(String value, String name) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireIdentity(String value, String name) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCluster(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("cluster ID is malformed"); + } + } + + private static void requireRevision(String value, String name) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is unavailable", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java new file mode 100644 index 0000000000..a2a5d47715 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -0,0 +1,1290 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ReceiverPodPin; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +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; + +/** + * Default-inactive reader for one protected expected validator inventory and its live Kubernetes + * Deployment/Pod observations. The snapshot is non-authorizing evidence only; it does not prove + * per-Pod token acceptance, readiness completeness, promotion eligibility, or convergence. + */ +public final class AccountJwtValidatorInventorySource { + private static final int MAX_PAGES = 16; + private static final int MAX_PODS_PER_VALIDATOR = 128; + private static final int MAX_CANONICAL_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v2"; + private static final String SELF_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern IMAGE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern OPERATION_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POD_TEMPLATE_HASH = Pattern.compile("[a-z0-9]{5,20}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtValidatorInventoryBinding inventoryBinding; + private final Clock clock; + + /** No Spring stereotype or automatic activation is provided. */ + public AccountJwtValidatorInventorySource( + AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding, + Clock clock) { + this.apiBinding = + Objects.requireNonNull(apiBinding, "protected Kubernetes API binding is required"); + this.inventoryBinding = + Objects.requireNonNull( + inventoryBinding, "protected validator inventory binding is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Produces a fresh immutable observation. Any unavailable, changed, partial, ambiguous, legacy, + * or unpinned state is returned as one redacted failure; no Kubernetes response body is retained. + */ + public InventorySnapshot observe() { + return observeInternal(null); + } + + /** + * Produces an observation bound to an Account-selected durable generation operation. Only an + * initial operation with no durable or published active signer may enumerate non-ready Running + * Pods as candidates; those candidates still require the existing authenticated per-Pod probes + * before they can satisfy a promotion proof. + */ + public InventorySnapshot observe(ObservationContext observationContext) { + return observeInternal(Objects.requireNonNull(observationContext)); + } + + private InventorySnapshot observeInternal(ObservationContext observationContext) { + ProtectedInventory expected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + boolean requireOrdinaryReady = + observationContext == null || observationContext.purpose().requiresOrdinaryReady(); + try (ApiOperation operation = apiBinding.beginOperation()) { + ParsedBinding api = operation.binding(); + if (!expected.matchesApiBinding(api)) { + throw new InventoryUnavailableException(); + } + verifyApiIdentity(operation, expected); + List observations = new ArrayList<>(); + for (ValidatorExpectation validator : expected.validators()) { + DeploymentObservation beforeDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List beforePods = + readPods(operation, expected, validator, beforeDeployment, requireOrdinaryReady); + List beforeReplicaSets = + readReplicaSets( + operation, expected, validator, beforeDeployment, beforePods, requireOrdinaryReady); + DeploymentObservation afterDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List afterPods = + readPods(operation, expected, validator, afterDeployment, requireOrdinaryReady); + List afterReplicaSets = + readReplicaSets( + operation, expected, validator, afterDeployment, afterPods, requireOrdinaryReady); + if (!beforeDeployment.equals(afterDeployment) + || !beforePods.equals(afterPods) + || !beforeReplicaSets.equals(afterReplicaSets)) { + throw new InventoryUnavailableException(); + } + observations.add( + new ValidatorObservation( + validator.validatorId(), + beforeDeployment.name(), + beforeDeployment.uid(), + beforeDeployment.generation(), + beforeDeployment.resourceVersion(), + beforeDeployment.replicas(), + beforeDeployment.image(), + beforeDeployment.verifierConfigSha256(), + validator.maxCacheAgeSeconds(), + validator.profiles(), + beforePods, + beforeReplicaSets)); + } + verifyApiIdentity(operation, expected); + ProtectedInventory afterExpected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + if (!expected.bindingDigest().equals(afterExpected.bindingDigest()) + || !expected.configRevision().equals(afterExpected.configRevision())) { + throw new InventoryUnavailableException(); + } + Instant observedAt = clock.instant(); + if (observedAt == null || observedAt.isBefore(Instant.EPOCH)) { + throw new InventoryUnavailableException(); + } + return createSnapshot(expected, observations, observedAt, observationContext); + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Do not expose tokens, API bodies, file paths, parser details, or exception causes. + throw new InventoryUnavailableException(); + } + } + + private static void verifyApiIdentity(ApiOperation operation, ProtectedInventory expected) { + ParsedBinding binding = operation.binding(); + if (!expected.matchesApiBinding(binding)) { + throw new InventoryUnavailableException(); + } + ApiResponse selfReview = + operation.send( + AccountJwtJwksApiBinding.ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + SELF_REVIEW_REQUEST.getBytes(StandardCharsets.UTF_8)); + if (selfReview.statusCode() != 200 && selfReview.statusCode() != 201) { + throw new InventoryUnavailableException(); + } + JsonNode review = parseJson(selfReview.body()); + JsonNode status = review.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + JsonNode username = userInfo == null ? null : userInfo.get("username"); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(review.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(review.get("kind"))) + || !binding.expectedApiUsername().equals(text(username)) + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new InventoryUnavailableException(); + } + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + expected.expectedClusterIncarnationUid()); + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_TARGET_NAMESPACE, null), + expected.namespace(), + expected.expectedNamespaceUid()); + } + + private static void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + } + + private static DeploymentObservation readDeployment( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + boolean requireOrdinaryReady) { + ApiResponse response = operation.readValidatorDeployment(inventory, expected); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"Deployment".equals(text(root.get("kind"))) + || metadata == null + || !expected.deploymentName().equals(text(metadata.get("name"))) + || !inventory.namespace().equals(text(metadata.get("namespace"))) + || !expected.deploymentUid().equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || spec == null + || status == null + || selector == null + || !selectorMatches(selector.get("matchLabels"), expected.selector()) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + int updatedReplicas = exactInt(status.get("updatedReplicas"), 0, 128); + int availableReplicas = + observedReplicaCount(status, "availableReplicas", !requireOrdinaryReady); + int unavailableReplicas = + status.has("unavailableReplicas") && !status.get("unavailableReplicas").isNull() + ? exactInt(status.get("unavailableReplicas"), 0, 128) + : 0; + if (replicas != expected.replicas() + || positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || updatedReplicas != replicas + || availableReplicas > readyReplicas + || unavailableReplicas > replicas + || (requireOrdinaryReady + && (readyReplicas != replicas + || availableReplicas != replicas + || unavailableReplicas != 0))) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + return new DeploymentObservation( + expected.deploymentName(), + expected.deploymentUid(), + resourceVersion, + generation, + replicas, + readyReplicas, + availableReplicas, + container.image(), + container.runtimeConfigSha256()); + } + + private static int observedReplicaCount( + JsonNode status, String fieldName, boolean allowOmittedZero) { + if (!status.has(fieldName)) { + if (allowOmittedZero) { + // Kubernetes omits zero-valued optional status replica counts. This is safe only for the + // owner-bound initial candidate observation; strict readiness still requires both fields. + return 0; + } + throw new InventoryUnavailableException(); + } + return exactInt(status.get(fieldName), 0, 128); + } + + private static List readPods( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + String continuation = null; + String listResourceVersion = null; + int pageCount = 0; + List pods = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podNames = new LinkedHashSet<>(); + do { + if (++pageCount > MAX_PAGES) { + throw new InventoryUnavailableException(); + } + ApiResponse response = operation.listValidatorPods(inventory, expected, continuation); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode items = root.get("items"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"PodList".equals(text(root.get("kind"))) + || metadata == null + || items == null + || !items.isArray()) { + throw new InventoryUnavailableException(); + } + String pageVersion = resourceVersion(text(metadata.get("resourceVersion"))); + if (listResourceVersion == null) { + listResourceVersion = pageVersion; + } else if (!listResourceVersion.equals(pageVersion)) { + throw new InventoryUnavailableException(); + } + for (JsonNode item : items) { + if (pods.size() >= MAX_PODS_PER_VALIDATOR) { + throw new InventoryUnavailableException(); + } + PodObservation pod = + parsePod(item, inventory.namespace(), expected, deployment, requireOrdinaryReady); + if (!podUids.add(pod.uid()) || !podNames.add(pod.name())) { + throw new InventoryUnavailableException(); + } + pods.add(pod); + } + JsonNode continueNode = metadata.get("continue"); + if (continueNode == null || continueNode.isNull() || !continueNode.isTextual()) { + continuation = null; + } else { + continuation = continueNode.asText(); + if (continuation.isEmpty()) { + continuation = null; + } else if (continuation.length() > 2048) { + throw new InventoryUnavailableException(); + } + } + } while (continuation != null); + if (pods.size() != expected.replicas()) { + throw new InventoryUnavailableException(); + } + pods.sort(Comparator.comparing(PodObservation::uid)); + List observedPodUids = pods.stream().map(PodObservation::uid).toList(); + List protectedPodUids = + expected.receiverPods().stream().map(ReceiverPodPin::podUid).sorted().toList(); + if (!observedPodUids.equals(protectedPodUids)) { + throw new InventoryUnavailableException(); + } + return List.copyOf(pods); + } + + private static PodObservation parsePod( + JsonNode pod, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + if (pod == null || pod.isNull()) { + throw new InventoryUnavailableException(); + } + JsonNode metadata = pod.get("metadata"); + JsonNode spec = pod.get("spec"); + JsonNode status = pod.get("status"); + if (!"v1".equals(text(pod.get("apiVersion"))) + || !"Pod".equals(text(pod.get("kind"))) + || metadata == null + || spec == null + || status == null + || !namespace.equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || !labelsMatch(metadata.get("labels"), expected.selector()) + || !"Running".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + String name = dnsLabel(text(metadata.get("name"))); + String uid = canonicalUid(text(metadata.get("uid"))); + String podIp = canonicalPodIp(text(status.get("podIP"))); + ReceiverPodPin receiverPin = + expected.receiverPods().stream() + .filter(pin -> pin.podUid().equals(uid)) + .findFirst() + .orElseThrow(InventoryUnavailableException::new); + if (!receiverPin.podIp().equals(podIp)) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + String templateHash = podTemplateHash(metadata.get("labels")); + JsonNode owners = metadata.get("ownerReferences"); + if (owners == null || !owners.isArray() || owners.size() != 1) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"ReplicaSet".equals(text(owner.get("kind"))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String ownerName = dnsLabel(text(owner.get("name"))); + String ownerUid = canonicalUid(text(owner.get("uid"))); + ContainerConfig container = + findVerifiedContainer(spec.get("containers"), expected, spec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + verifyReadyCondition(status.get("conditions"), requireOrdinaryReady); + verifyContainerReady( + status.get("containerStatuses"), expected, deployment.image(), requireOrdinaryReady); + return new PodObservation( + name, + uid, + resourceVersion, + ownerName, + ownerUid, + templateHash, + deployment.image(), + deployment.verifierConfigSha256(), + podIp, + podEndpoint(podIp, expected.receiverPort()), + expected.receiverServiceUri(), + receiverPin.leafSpkiSha256()); + } + + private static List readReplicaSets( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + List pods, + boolean requireOrdinaryReady) { + Map observedOwners = new LinkedHashMap<>(); + Map templateHashes = new LinkedHashMap<>(); + for (PodObservation pod : pods) { + String prior = observedOwners.putIfAbsent(pod.ownerName(), pod.ownerUid()); + String priorHash = templateHashes.putIfAbsent(pod.ownerName(), pod.podTemplateHash()); + if ((prior != null && !prior.equals(pod.ownerUid())) + || (priorHash != null && !priorHash.equals(pod.podTemplateHash()))) { + throw new InventoryUnavailableException(); + } + } + List observations = new ArrayList<>(observedOwners.size()); + for (Map.Entry owner : observedOwners.entrySet()) { + ApiResponse response = operation.readValidatorReplicaSet(inventory, expected, owner.getKey()); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + observations.add( + parseReplicaSet( + response.body(), + inventory.namespace(), + expected, + deployment, + owner.getKey(), + owner.getValue(), + templateHashes.get(owner.getKey()), + requireOrdinaryReady)); + } + observations.sort(Comparator.comparing(ReplicaSetObservation::uid)); + return List.copyOf(observations); + } + + private static ReplicaSetObservation parseReplicaSet( + byte[] responseBody, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + String expectedName, + String expectedUid, + String expectedTemplateHash, + boolean requireOrdinaryReady) { + JsonNode root = parseJson(responseBody); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode owners = metadata == null ? null : metadata.get("ownerReferences"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"ReplicaSet".equals(text(root.get("kind"))) + || metadata == null + || !expectedName.equals(text(metadata.get("name"))) + || !namespace.equals(text(metadata.get("namespace"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || owners == null + || !owners.isArray() + || owners.size() != 1 + || spec == null + || status == null + || selector == null + || !replicaSetSelectorMatches( + selector.get("matchLabels"), expected.selector(), expectedTemplateHash) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || !expectedTemplateHash.equals( + text(templateMetadata.get("labels").get("pod-template-hash"))) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"Deployment".equals(text(owner.get("kind"))) + || !deployment.name().equals(text(owner.get("name"))) + || !deployment.uid().equals(canonicalUid(text(owner.get("uid")))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + if (positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || replicas != expected.replicas() + || (requireOrdinaryReady && readyReplicas != replicas)) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + return new ReplicaSetObservation( + expectedName, + expectedUid, + resourceVersion, + generation, + replicas, + deployment.name(), + deployment.uid(), + expectedTemplateHash, + container.image(), + container.runtimeConfigSha256()); + } + + private static boolean replicaSetSelectorMatches( + JsonNode actual, Map expected, String expectedTemplateHash) { + if (actual == null + || !actual.isObject() + || expectedTemplateHash == null + || actual.size() != expected.size() + 1 + || !expectedTemplateHash.equals(text(actual.get("pod-template-hash")))) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(actual.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static String podTemplateHash(JsonNode labels) { + if (labels == null || !labels.isObject()) { + throw new InventoryUnavailableException(); + } + String value = text(labels.get("pod-template-hash")); + if (value == null || !POD_TEMPLATE_HASH.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static ContainerConfig findVerifiedContainer( + JsonNode containers, ValidatorExpectation expected, JsonNode volumes) { + if (containers == null + || !containers.isArray() + || containers.isEmpty() + || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode selected = null; + for (JsonNode container : containers) { + String name = text(container.get("name")); + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningSecretMounts(container.get("volumeMounts")); + if (expected.containerName().equals(name)) { + if (selected != null) { + throw new InventoryUnavailableException(); + } + selected = container; + } + } + rejectSigningSecretVolumes(volumes); + if (selected == null || !expected.image().equals(text(selected.get("image")))) { + throw new InventoryUnavailableException(); + } + JsonNode env = selected.get("env"); + JsonNode configNode = null; + Set environmentNames = new LinkedHashSet<>(); + if (env != null && !env.isNull()) { + if (!env.isArray() || env.size() > 256) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String envName = text(variable.get("name")); + if (envName == null || !environmentNames.add(envName)) { + throw new InventoryUnavailableException(); + } + if (RUNTIME_CONFIG_ENV.equals(envName)) { + if (variable.has("valueFrom") + || !expected.canonicalRuntimeConfig().equals(text(variable.get("value")))) { + throw new InventoryUnavailableException(); + } + configNode = variable; + } + if ("SPRING_APPLICATION_JSON".equals(envName) + || "JAVA_TOOL_OPTIONS".equals(envName) + || "JDK_JAVA_OPTIONS".equals(envName)) { + throw new InventoryUnavailableException(); + } + } + } + if (configNode == null) { + throw new InventoryUnavailableException(); + } + return new ContainerConfig( + expected.image(), + sha256(expected.canonicalRuntimeConfig().getBytes(StandardCharsets.UTF_8))); + } + + private static void rejectSigningMaterialEnvironment(JsonNode env) { + if (env == null || env.isNull()) { + return; + } + if (!env.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String name = text(variable.get("name")); + if (name != null + && (name.equals("FIREMUD_AUTH_JWT_SECRET") + || name.equals("FIREMUD_AUTH_JWT_SECRET_PATH") + || name.contains("JWT_HMAC") + || name.contains("JWT_SIGNING_KEY"))) { + throw new InventoryUnavailableException(); + } + JsonNode valueFrom = variable.get("valueFrom"); + JsonNode secretKeyRef = valueFrom == null ? null : valueFrom.get("secretKeyRef"); + if (secretKeyRef != null && !secretKeyRef.isNull()) { + String secretName = text(secretKeyRef.get("name")); + if ("jwt-signing-keys".equals(secretName)) { + throw new InventoryUnavailableException(); + } + } + } + } + + private static void rejectSigningSecretMounts(JsonNode mounts) { + if (mounts == null || mounts.isNull()) { + return; + } + if (!mounts.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode mount : mounts) { + String name = text(mount.get("name")); + String path = text(mount.get("mountPath")); + if ("jwt-signing-keys".equals(name) + || (path != null && path.startsWith("/var/run/secrets/firemud/jwt"))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void rejectSigningSecretVolumes(JsonNode volumes) { + if (volumes == null || volumes.isNull()) { + return; + } + if (!volumes.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode volume : volumes) { + String name = text(volume.get("name")); + JsonNode secret = volume.get("secret"); + if ("jwt-signing-keys".equals(name) + || (secret != null + && !secret.isNull() + && "jwt-signing-keys".equals(text(secret.get("secretName"))))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void verifyReadyCondition(JsonNode conditions, boolean requireOrdinaryReady) { + if (conditions == null || !conditions.isArray() || conditions.size() > 64) { + throw new InventoryUnavailableException(); + } + boolean ready = false; + for (JsonNode condition : conditions) { + if ("Ready".equals(text(condition.get("type")))) { + String status = text(condition.get("status")); + if (ready || (!"True".equals(status) && !"False".equals(status))) { + throw new InventoryUnavailableException(); + } + if (requireOrdinaryReady && !"True".equals(status)) { + throw new InventoryUnavailableException(); + } + ready = true; + } + } + if (!ready) { + throw new InventoryUnavailableException(); + } + } + + private static void verifyContainerReady( + JsonNode statuses, + ValidatorExpectation expected, + String expectedImage, + boolean requireOrdinaryReady) { + if (statuses == null || !statuses.isArray() || statuses.isEmpty() || statuses.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode found = null; + for (JsonNode status : statuses) { + if (expected.containerName().equals(text(status.get("name")))) { + if (found != null) { + throw new InventoryUnavailableException(); + } + found = status; + } + } + String imageId = found == null ? null : text(found.get("imageID")); + String digest = imageDigest(imageId); + String expectedDigest = expected.image().substring(expected.image().lastIndexOf('@') + 1); + Boolean ready = found == null ? null : booleanValue(found.get("ready")); + if (found == null + || ready == null + || (requireOrdinaryReady && !ready) + || !expectedDigest.equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + private static InventorySnapshot createSnapshot( + ProtectedInventory expected, + List validators, + Instant observedAt, + ObservationContext observationContext) { + List sorted = + validators.stream() + .sorted(Comparator.comparing(ValidatorObservation::validatorId)) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", INVENTORY_DOMAIN); + // Acquisition time is independently bounded freshness metadata, not inventory content. The + // v2 digest must remain stable across an unchanged later reread while retaining this time in + // the immutable snapshot row and in the in-memory observation. + preimage.put("environmentId", expected.environmentId()); + preimage.put("clusterId", expected.clusterId()); + preimage.put("clusterIncarnationUid", expected.expectedClusterIncarnationUid()); + preimage.put("namespace", expected.namespace()); + preimage.put("namespaceUid", expected.expectedNamespaceUid()); + preimage.put("apiBindingRevision", expected.apiBindingRevision()); + preimage.put("apiBindingDigest", expected.apiBindingDigest()); + preimage.put("inventoryBindingRevision", expected.configRevision()); + preimage.put("inventoryBindingDigest", expected.bindingDigest()); + if (observationContext != null) { + preimage.put("observationContext", observationContext.canonicalMap()); + } + preimage.put( + "validators", + sorted.stream().map(AccountJwtValidatorInventorySource::validatorMap).toList()); + byte[] canonicalSnapshot = canonicalBytes(preimage); + if (canonicalSnapshot.length > MAX_CANONICAL_SNAPSHOT_BYTES) { + throw new InventoryUnavailableException(); + } + String digest = sha256(canonicalSnapshot); + return new InventorySnapshot( + observedAt, + expected.environmentId(), + expected.clusterId(), + expected.expectedClusterIncarnationUid(), + expected.namespace(), + expected.expectedNamespaceUid(), + expected.apiBindingRevision(), + expected.apiBindingDigest(), + expected.configRevision(), + expected.bindingDigest(), + sorted, + Optional.ofNullable(observationContext), + canonicalSnapshot, + digest); + } + + private static Map validatorMap(ValidatorObservation validator) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", validator.pods().stream().map(AccountJwtValidatorInventorySource::podMap).toList()); + result.put("receiverServiceUri", validator.pods().getFirst().receiverServiceUri()); + result.put("receiverPort", validator.pods().getFirst().endpoint().getPort()); + result.put( + "replicaSets", + validator.replicaSets().stream() + .map(AccountJwtValidatorInventorySource::replicaSetMap) + .toList()); + return result; + } + + private static Map replicaSetMap(ReplicaSetObservation replicaSet) { + return Map.of( + "name", replicaSet.name(), + "uid", replicaSet.uid(), + "resourceVersion", replicaSet.resourceVersion(), + "generation", Long.toString(replicaSet.generation()), + "replicas", Integer.toString(replicaSet.replicas()), + "ownerDeploymentName", replicaSet.ownerDeploymentName(), + "ownerDeploymentUid", replicaSet.ownerDeploymentUid(), + "podTemplateHash", replicaSet.podTemplateHash(), + "image", replicaSet.image(), + "verifierConfigSha256", replicaSet.verifierConfigSha256()); + } + + private static Map podMap(PodObservation pod) { + return Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256())); + } + + private static URI podEndpoint(String podIp, int port) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return URI.create("grpcs://" + host + ":" + port); + } + + private static String canonicalPodIp(String value) { + try { + return AccountJwtValidatorInventoryBinding.canonicalPodIp(value); + } catch (RuntimeException failure) { + throw new InventoryUnavailableException(); + } + } + + private static boolean selectorMatches(JsonNode actual, Map expected) { + if (actual == null || !actual.isObject() || actual.size() != expected.size()) { + return false; + } + return labelsMatch(actual, expected); + } + + private static boolean labelsMatch(JsonNode labels, Map expected) { + if (labels == null || !labels.isObject()) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(labels.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 1024 * 1024) { + throw new InventoryUnavailableException(); + } + try { + JsonNode parsed = JSON.readTree(decodeUtf8(bytes)); + if (parsed == null || !parsed.isObject()) { + throw new InventoryUnavailableException(); + } + return parsed; + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static String imageDigest(String imageId) { + if (imageId == null) { + throw new InventoryUnavailableException(); + } + int marker = imageId.lastIndexOf("sha256:"); + if (marker < 0) { + throw new InventoryUnavailableException(); + } + String digest = imageId.substring(marker); + if (!IMAGE_DIGEST.matcher(digest).matches()) { + throw new InventoryUnavailableException(); + } + return digest; + } + + private static String canonicalUid(String value) { + if (value == null || !UID.matcher(value).matches() || value.startsWith("00000000-")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String resourceVersion(String value) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String dnsLabel(String value) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static long positiveLong(JsonNode node) { + long value = exactLong(node, 1L, Long.MAX_VALUE); + return value; + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return (int) value; + } + + private static long exactLong(JsonNode node, long minimum, long maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return value; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw new InventoryUnavailableException(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private record ContainerConfig(String image, String runtimeConfigSha256) {} + + private record DeploymentObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + int readyReplicas, + int availableReplicas, + String image, + String verifierConfigSha256) {} + + public record ReplicaSetObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + String ownerDeploymentName, + String ownerDeploymentUid, + String podTemplateHash, + String image, + String verifierConfigSha256) {} + + /** No Pod or Kubernetes API body is retained, only closed non-secret identity fields. */ + public record PodObservation( + String name, + String uid, + String resourceVersion, + String ownerName, + String ownerUid, + String podTemplateHash, + String image, + String verifierConfigSha256, + String podIp, + URI endpoint, + String receiverServiceUri, + String leafSpkiSha256) {} + + public record ValidatorObservation( + String validatorId, + String deploymentName, + String deploymentUid, + long deploymentGeneration, + String deploymentResourceVersion, + int replicas, + String image, + String verifierConfigSha256, + int maxCacheAgeSeconds, + List profiles, + List pods, + List replicaSets) { + public ValidatorObservation { + profiles = List.copyOf(profiles); + pods = List.copyOf(pods); + replicaSets = List.copyOf(replicaSets); + } + } + + /** + * Account-owner-derived context for one validator inventory acquisition. Bootstrap candidate + * observation is available only for the exact current operation whose active signer fence is + * absent; the repository re-derives and checks this context before consuming the snapshot. + */ + public record ObservationContext( + ObservationPurpose purpose, UUID operationId, String operationDigest) { + public ObservationContext { + Objects.requireNonNull(purpose, "Inventory observation purpose is required"); + Objects.requireNonNull(operationId, "Inventory observation operation is required"); + if (operationId.version() != 4 + || operationId.variant() != 2 + || operationDigest == null + || !OPERATION_DIGEST.matcher(operationDigest).matches()) { + throw new InventoryUnavailableException(); + } + } + + public boolean isInitialNoActiveSigner() { + return purpose == ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + } + + private Map canonicalMap() { + return Map.of( + "purpose", purpose.name(), + "operationId", operationId.toString(), + "operationDigest", operationDigest); + } + } + + public enum ObservationPurpose { + STRICT_READY, + INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + + private boolean requiresOrdinaryReady() { + return this == STRICT_READY; + } + } + + public static final class InventorySnapshot { + private final Instant observedAt; + private final String environmentId; + private final String clusterId; + private final String clusterIncarnationUid; + private final String namespace; + private final String namespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String inventoryBindingRevision; + private final String inventoryBindingDigest; + private final List validators; + private final Optional observationContext; + private final byte[] canonicalBytes; + private final String digest; + + private InventorySnapshot( + Instant observedAt, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + List validators, + Optional observationContext, + byte[] canonicalBytes, + String digest) { + this.observedAt = Objects.requireNonNull(observedAt); + this.environmentId = Objects.requireNonNull(environmentId); + this.clusterId = Objects.requireNonNull(clusterId); + this.clusterIncarnationUid = Objects.requireNonNull(clusterIncarnationUid); + this.namespace = Objects.requireNonNull(namespace); + this.namespaceUid = Objects.requireNonNull(namespaceUid); + this.apiBindingRevision = Objects.requireNonNull(apiBindingRevision); + this.apiBindingDigest = Objects.requireNonNull(apiBindingDigest); + this.inventoryBindingRevision = Objects.requireNonNull(inventoryBindingRevision); + this.inventoryBindingDigest = Objects.requireNonNull(inventoryBindingDigest); + this.validators = List.copyOf(validators); + this.observationContext = Objects.requireNonNull(observationContext); + this.canonicalBytes = Objects.requireNonNull(canonicalBytes).clone(); + this.digest = Objects.requireNonNull(digest); + if (this.canonicalBytes.length == 0 + || this.canonicalBytes.length > MAX_CANONICAL_SNAPSHOT_BYTES + || !sha256(this.canonicalBytes).equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + public Instant observedAt() { + return observedAt; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String clusterIncarnationUid() { + return clusterIncarnationUid; + } + + public String namespace() { + return namespace; + } + + public String namespaceUid() { + return namespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String inventoryBindingRevision() { + return inventoryBindingRevision; + } + + public String inventoryBindingDigest() { + return inventoryBindingDigest; + } + + public List validators() { + return validators; + } + + public Optional observationContext() { + return observationContext; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof InventorySnapshot that)) return false; + return observedAt.equals(that.observedAt) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && validators.equals(that.validators) + && observationContext.equals(that.observationContext) + && java.util.Arrays.equals(canonicalBytes, that.canonicalBytes) + && digest.equals(that.digest); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + observedAt, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + validators, + observationContext, + digest) + + java.util.Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventoryUnavailableException extends RuntimeException { + public InventoryUnavailableException() { + super("Account validator inventory is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java new file mode 100644 index 0000000000..2e1929da82 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -0,0 +1,1269 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded Account-local parser and correspondence proof for the interim mounted JWT signer. + * + *

This class exposes no general private-key operation or caller-facing token response. Its + * package-private signing operations are closed readiness probes and the exact Account-owned + * initial Game Session delegation candidate; compact bytes are delivered only to an owner callback + * and wiped after it returns. Local correspondence alone proves no lifecycle or authorization. + */ +public final class AccountMountedJwtSignerBundle { + public static final int MAX_PRIVATE_BUNDLE_BYTES = 64 * 1024; + public static final int MAX_PUBLIC_JWKS_BYTES = 256 * 1024; + private static final int MAX_READINESS_COMPACT_JWT_BYTES = 16 * 1024; + private static final int MAX_DELEGATION_COMPACT_JWT_BYTES = + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES; + private static final int MAX_RSA_BITS = 16_384; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_JWKS_KEYS = 64; + private static final int MAX_PRIVATE_KEY_DER_BYTES = 16 * 1024; + private static final int CHALLENGE_NONCE_BYTES = 32; + private static final SecureRandom CHALLENGE_RANDOM = new SecureRandom(); + private static final String ALGORITHM = "RS256"; + static final String READINESS_CANARY_PROFILE = "account-jwt-readiness-canary"; + static final String READINESS_CANARY_TYPE = "account_jwt_readiness_canary"; + static final String READINESS_CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + static final String READINESS_VALIDATOR_ID = "account-service"; + static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final String ISSUER = "firemud-account-service"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern FINGERPRINT = Pattern.compile("[0-9a-f]{64}"); + private static final Set PRIVATE_BUNDLE_FIELDS = + Set.of( + "version", + "environmentId", + "clusterId", + "namespace", + "operationId", + "generation", + "kid", + "algorithm", + "privateKeyPkcs8", + "publicKeyFingerprint"); + private static final Set JWKS_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final byte[] CHALLENGE_DOMAIN = + new byte[] { + 0, 'F', 'i', 'r', 'e', 'M', 'U', 'D', '/', 'A', 'c', 'c', 'o', 'u', 'n', 't', '/', 'm', 'o', + 'u', 'n', 't', 'e', 'd', '-', 's', 'i', 'g', 'n', 'e', 'r', '-', 'c', 'o', 'r', 'r', 'e', + 's', 'p', 'o', 'n', 'd', 'e', 'n', 'c', 'e', '/', 'v', '1', 0 + }; + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private AccountMountedJwtSignerBundle() {} + + /** + * Reads the explicitly configured Account-only private projection and public JWKS projection. + * Relative file paths must remain beneath their respective configured mount roots. Kubernetes + * projected-volume symlinks are accepted only when their resolved regular files stay beneath + * those roots. + */ + public static LocalObservation observeMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + return readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity) + .observation(); + } + + /** + * Signs only one fixed non-authorizing canary or one fixed-shape representative profile, passes + * the exact compact bytes transiently to the Account-owned callback, then wipes them and returns + * only their digest plus immutable planned identity. This method is package-private so no route, + * ordinary issuer, or other service can request arbitrary JWT signing from the mounted pending + * key. + */ + static SignedProbeDigest signReadinessProbeDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + ReadinessProbeSigningSpec spec, + ProbeDeliveryConsumer deliveryConsumer) { + Objects.requireNonNull(spec, "Readiness probe signing specification is required"); + Objects.requireNonNull(deliveryConsumer, "Readiness probe delivery consumer is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !spec.targetGeneration().equals(expectedIdentity.generation()) + || !spec.targetKid().equals(expectedIdentity.kid())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] deliveryBytes = null; + try { + SignedProbeDigest result; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + claims = canonicalJsonBytes(readinessClaims(spec)); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + result = + new SignedProbeDigest( + expectedIdentity.operationId(), + spec.validatorId(), + spec.probeKind(), + spec.tokenProfile(), + spec.audience(), + spec.jti(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + spec.issuedAtEpochSecond(), + spec.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } + deliveryBytes = compactBytes.clone(); + deliveryConsumer.persistAttemptAndDeliver(result, deliveryBytes); + if (!sha256(deliveryBytes).equals(result.compactTokenSha256())) { + throw invalid(); + } + return result; + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(deliveryBytes); + } + } + + /** + * Signs only the exact Account-owned, initial Game Session delegation claim shape with the + * already committed signer identity supplied by the owner service. The compact credential is + * passed once to the Account persistence callback and wiped before this method returns. + */ + static SignedDelegationDigest signCommittedGameplayDelegationDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + DelegationSigningSpec spec, + DelegationCandidateConsumer candidateConsumer) { + Objects.requireNonNull(spec, "Gameplay delegation signing specification is required"); + Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + AccountGameplayDelegationPendingIdentity identity = spec.identity(); + AccountAuthoritySnapshot authority = spec.authoritySnapshot(); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] callbackBytes = null; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + Map delegation = delegationClaims(identity, authority); + if (spec.bound().isPresent()) { + var bound = spec.bound().orElseThrow(); + delegation.put("tenantId", bound.tenantId()); + delegation.put("authorityTuple", bound.authorityTuple()); + delegation.put("membershipVersion", bound.membershipVersion()); + } + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(delegation); + claims = canonicalJsonBytes(delegation); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_DELEGATION_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + SignedDelegationDigest digest = + new SignedDelegationDigest( + identity.operationId(), + identity.requestId(), + identity.tokenJti(), + expectedIdentity.operationId(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + callbackBytes = compactBytes.clone(); + try { + candidateConsumer.bindExactCandidate(digest, callbackBytes); + } catch (RuntimeException failure) { + // Callback exception chains must never retain the transient compact credential. + throw invalid(); + } + if (!sha256(callbackBytes).equals(digest.compactTokenSha256())) { + throw invalid(); + } + return digest; + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(callbackBytes); + } + } + + private static Map delegationClaims( + AccountGameplayDelegationPendingIdentity identity, AccountAuthoritySnapshot authority) { + if (!authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", authority.accountId().toString()); + claims.put("jti", identity.tokenJti().toString()); + claims.put("accountId", authority.accountId().toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", identity.issuedAtEpochSecond()); + claims.put("nbf", identity.notBeforeEpochSecond()); + claims.put("exp", identity.expiresAtEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", Long.toString(authority.issuanceFence())); + return claims; + } + + private static VerifiedMountedSigner readAndVerifyMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + byte[] privateBytes = null; + try { + if (expectedIdentity == null) { + throw invalid(); + } + validateIdentity(expectedIdentity); + Path privateFile = resolveMountedFile(privateMountRoot, privateBundlePath); + Path publicFile = resolveMountedFile(publicMountRoot, publicJwksPath); + privateBytes = readBounded(privateFile, MAX_PRIVATE_BUNDLE_BYTES); + ParsedPrivateBundle privateBundle = parsePrivateBundle(privateBytes); + Arrays.fill(privateBytes, (byte) 0); + privateBytes = null; + requireExpectedIdentity(privateBundle.identity(), expectedIdentity); + + byte[] publicBytes = readBounded(publicFile, MAX_PUBLIC_JWKS_BYTES); + Map publicKeys; + try { + publicKeys = parsePublicJwks(publicBytes); + } finally { + Arrays.fill(publicBytes, (byte) 0); + } + RSAPublicKey publicKey = publicKeys.get(expectedIdentity.kid()); + if (publicKey == null + || !publicKey.getModulus().equals(privateBundle.publicModulus()) + || !publicKey.getPublicExponent().equals(privateBundle.publicExponent())) { + throw invalid(); + } + String fingerprint = fingerprint(publicKey.getModulus(), publicKey.getPublicExponent()); + if (!fingerprint.equals(expectedIdentity.publicKeyFingerprint()) + || !fingerprint.equals(privateBundle.identity().publicKeyFingerprint())) { + throw invalid(); + } + proveCorrespondence(privateBundle.privateKey(), publicKey); + return new VerifiedMountedSigner( + new LocalObservation(expectedIdentity, fingerprint), + privateBundle.privateKey(), + publicKey); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + // Do not retain path, parser, key, or mounted-file details in a caller-visible failure. + throw invalid(); + } finally { + if (privateBytes != null) { + Arrays.fill(privateBytes, (byte) 0); + } + } + } + + private static Map readinessClaims(ReadinessProbeSigningSpec spec) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", spec.jti().toString()); + claims.put("aud", spec.audience()); + claims.put("iat", spec.issuedAtEpochSecond()); + claims.put("nbf", spec.issuedAtEpochSecond()); + claims.put("exp", spec.expiresAtEpochSecond()); + if (spec.probeKind() == ProbeKind.CANARY) { + claims.put("tokenProfile", READINESS_CANARY_PROFILE); + claims.put("tokenType", READINESS_CANARY_TYPE); + return claims; + } + if (ControlUiJwtProfileValidator.PROFILE.equals(spec.tokenProfile()) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + claims.put("scopedRoles", Map.of()); + } + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(spec.tokenProfile()); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", initialCounter); + Map authorityTuple = new LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", initialCounter); + authorityTuple.put("accountAuthorityGeneration", initialCounter); + authorityTuple.put("tenantAuthorityGeneration", Map.of()); + authorityTuple.put("membershipAuthorityGeneration", Map.of()); + authorityTuple.put("privateRealmGrantVersions", List.of()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + return claims; + } + + private static byte[] canonicalJsonBytes(Map fields) throws Exception { + String json = STRICT_JSON.writeValueAsString(fields); + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } + + private static byte[] joinCompactParts(byte[] header, byte[] claims, byte[] signature) { + int signatureLength = signature == null ? 0 : signature.length; + int separatorCount = signature == null ? 1 : 2; + byte[] compact = new byte[header.length + claims.length + signatureLength + separatorCount]; + int offset = 0; + System.arraycopy(header, 0, compact, offset, header.length); + offset += header.length; + compact[offset++] = (byte) '.'; + System.arraycopy(claims, 0, compact, offset, claims.length); + offset += claims.length; + if (signature != null) { + compact[offset++] = (byte) '.'; + System.arraycopy(signature, 0, compact, offset, signature.length); + } + return compact; + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + /** + * Builds the binary, domain-separated challenge used only by the local correspondence proof. Its + * leading NUL makes it structurally distinct from an ASCII compact JWT serialization. + */ + static byte[] correspondenceChallenge(byte[] nonce) { + if (nonce == null || nonce.length != CHALLENGE_NONCE_BYTES) { + throw invalid(); + } + byte[] challenge = Arrays.copyOf(CHALLENGE_DOMAIN, CHALLENGE_DOMAIN.length + nonce.length); + System.arraycopy(nonce, 0, challenge, CHALLENGE_DOMAIN.length, nonce.length); + return challenge; + } + + static void validateStrongRsaCrtPrivateKey(PrivateKey privateKey) { + if (!(privateKey instanceof RSAPrivateCrtKey rsaPrivateKey) + || !"RSA".equalsIgnoreCase(privateKey.getAlgorithm())) { + throw invalid(); + } + BigInteger modulus = rsaPrivateKey.getModulus(); + BigInteger publicExponent = rsaPrivateKey.getPublicExponent(); + BigInteger privateExponent = rsaPrivateKey.getPrivateExponent(); + BigInteger primeP = rsaPrivateKey.getPrimeP(); + BigInteger primeQ = rsaPrivateKey.getPrimeQ(); + BigInteger primeExponentP = rsaPrivateKey.getPrimeExponentP(); + BigInteger primeExponentQ = rsaPrivateKey.getPrimeExponentQ(); + BigInteger crtCoefficient = rsaPrivateKey.getCrtCoefficient(); + if (!positive(modulus) + || modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !BigInteger.valueOf(65_537).equals(publicExponent) + || !positive(privateExponent) + || !positive(primeP) + || !positive(primeQ) + || primeP.equals(primeQ) + || !positive(primeExponentP) + || !positive(primeExponentQ) + || !positive(crtCoefficient)) { + throw invalid(); + } + BigInteger pMinusOne = primeP.subtract(BigInteger.ONE); + BigInteger qMinusOne = primeQ.subtract(BigInteger.ONE); + BigInteger lambda = pMinusOne.divide(pMinusOne.gcd(qMinusOne)).multiply(qMinusOne); + if (!primeP.multiply(primeQ).equals(modulus) + || !privateExponent.multiply(publicExponent).mod(lambda).equals(BigInteger.ONE) + || !privateExponent.mod(pMinusOne).equals(primeExponentP) + || !privateExponent.mod(qMinusOne).equals(primeExponentQ) + || !primeQ.modInverse(primeP).equals(crtCoefficient)) { + throw invalid(); + } + } + + private static void validateIdentity(ExpectedIdentity identity) { + if (!validIdentityValue(identity.environmentId()) + || !validIdentityValue(identity.clusterId()) + || !validIdentityValue(identity.namespace()) + || !validUuidV4(identity.operationId()) + || identity.generation() == null + || !GENERATION.matcher(identity.generation()).matches() + || identity.kid() == null + || !KID.matcher(identity.kid()).matches() + || identity.publicKeyFingerprint() == null + || !FINGERPRINT.matcher(identity.publicKeyFingerprint()).matches()) { + throw invalid(); + } + } + + private static boolean validIdentityValue(String value) { + if (value == null || value.isBlank() || value.length() > 128) { + return false; + } + for (int index = 0; index < value.length(); index++) { + if (Character.isISOControl(value.charAt(index))) { + return false; + } + } + return true; + } + + private static boolean validUuidV4(String value) { + if (value == null) { + return false; + } + try { + UUID uuid = UUID.fromString(value); + return uuid.toString().equals(value) && uuid.version() == 4 && uuid.variant() == 2; + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void requireExpectedIdentity(ExpectedIdentity actual, ExpectedIdentity expected) { + if (!actual.equals(expected)) { + throw invalid(); + } + } + + private static ParsedPrivateBundle parsePrivateBundle(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PRIVATE_BUNDLE_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, PRIVATE_BUNDLE_FIELDS); + if (root.size() != PRIVATE_BUNDLE_FIELDS.size()) { + throw invalid(); + } + JsonNode version = root.get("version"); + if (version == null + || version.isNull() + || !version.isIntegralNumber() + || !version.canConvertToInt() + || version.intValue() != 1) { + throw invalid(); + } + ExpectedIdentity identity = + new ExpectedIdentity( + requiredText(root, "environmentId", 128), + requiredText(root, "clusterId", 128), + requiredText(root, "namespace", 128), + requiredText(root, "operationId", 36), + requiredText(root, "generation", 64), + requiredText(root, "kid", 64), + requiredText(root, "publicKeyFingerprint", 64)); + validateIdentity(identity); + if (!ALGORITHM.equals(requiredText(root, "algorithm", 8))) { + throw invalid(); + } + + String encodedPrivateKey = requiredText(root, "privateKeyPkcs8", 24 * 1024); + byte[] privateDer = decodeCanonicalBase64Url(encodedPrivateKey, MAX_PRIVATE_KEY_DER_BYTES); + try { + PrivateKey privateKey = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + validateStrongRsaCrtPrivateKey(privateKey); + RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; + byte[] canonicalEncoding = privateKey.getEncoded(); + try { + if (canonicalEncoding == null || !Arrays.equals(privateDer, canonicalEncoding)) { + throw invalid(); + } + } finally { + if (canonicalEncoding != null) { + Arrays.fill(canonicalEncoding, (byte) 0); + } + } + return new ParsedPrivateBundle( + privateKey, identity, rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()); + } finally { + Arrays.fill(privateDer, (byte) 0); + } + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static Map parsePublicJwks(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PUBLIC_JWKS_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, JWKS_FIELDS); + if (root.size() != 1) { + throw invalid(); + } + JsonNode keysNode = root.get("keys"); + if (keysNode == null + || !keysNode.isArray() + || keysNode.isEmpty() + || keysNode.size() > MAX_JWKS_KEYS) { + throw invalid(); + } + Map keys = new HashMap<>(); + Set seenKids = new HashSet<>(); + for (JsonNode jwk : keysNode) { + requireOnlyFields(jwk, JWK_FIELDS); + String keyType = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String algorithm = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String encodedModulus = requiredText(jwk, "n", 4_096); + String encodedExponent = requiredText(jwk, "e", 16); + if (!"RSA".equals(keyType) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || !seenKids.add(kid)) { + throw invalid(); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null) { + if (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw invalid(); + } + } + byte[] modulusBytes = decodeCanonicalBase64Url(encodedModulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(encodedExponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw invalid(); + } + BigInteger modulus = new BigInteger(1, modulusBytes); + BigInteger exponent = new BigInteger(1, exponentBytes); + if (modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !modulus.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponent)) { + throw invalid(); + } + RSAPublicKey publicKey = + (RSAPublicKey) + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulus, exponent)); + keys.put(kid, publicKey); + } finally { + Arrays.fill(modulusBytes, (byte) 0); + Arrays.fill(exponentBytes, (byte) 0); + } + } + return Map.copyOf(keys); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static JsonNode strictJson(byte[] contents) throws CharacterCodingException { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + if (text.startsWith("\uFEFF")) { + throw invalid(); + } + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || root.isNull()) { + throw invalid(); + } + return root; + } + + private static void requireOnlyFields(JsonNode node, Set allowedFields) { + if (node == null || !node.isObject()) { + throw invalid(); + } + for (Map.Entry field : node.properties()) { + if (!allowedFields.contains(field.getKey())) { + throw invalid(); + } + } + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null || value.isNull() || !value.isTextual()) { + throw invalid(); + } + String text = value.textValue(); + if (text == null || text.isEmpty() || text.length() > maxLength) { + throw invalid(); + } + return text; + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + if (encoded == null || encoded.isEmpty()) { + throw invalid(); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw invalid(); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean canonicalEncoding = canonical.length == encoded.length(); + for (int index = 0; canonicalEncoding && index < canonical.length; index++) { + canonicalEncoding = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !canonicalEncoding) { + Arrays.fill(decoded, (byte) 0); + throw invalid(); + } + return decoded; + } + + private static Path resolveMountedFile(Path configuredRoot, Path configuredRelativeFile) + throws IOException { + if (configuredRoot == null + || configuredRelativeFile == null + || !configuredRoot.isAbsolute() + || configuredRelativeFile.isAbsolute() + || configuredRelativeFile.toString().isBlank()) { + throw invalid(); + } + for (Path segment : configuredRelativeFile) { + if (".".equals(segment.toString()) || "..".equals(segment.toString())) { + throw invalid(); + } + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + Path resolvedFile = mountRoot.resolve(configuredRelativeFile).toRealPath(); + if (!resolvedFile.startsWith(mountRoot) + || !Files.isRegularFile(resolvedFile, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + return resolvedFile; + } + + private static byte[] readBounded(Path path, int maxBytes) throws IOException { + byte[] scratch = new byte[maxBytes + 1]; + try { + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(scratch); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > maxBytes) { + throw invalid(); + } + } + if (channel.position() != channel.size() || total != channel.size()) { + throw invalid(); + } + return Arrays.copyOf(scratch, total); + } + } finally { + Arrays.fill(scratch, (byte) 0); + } + } + + private static void proveCorrespondence(PrivateKey privateKey, RSAPublicKey publicKey) + throws GeneralSecurityException { + byte[] nonce = new byte[CHALLENGE_NONCE_BYTES]; + byte[] challenge = null; + byte[] signatureBytes = null; + try { + CHALLENGE_RANDOM.nextBytes(nonce); + challenge = correspondenceChallenge(nonce); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(privateKey); + signer.update(challenge); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(challenge); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + } finally { + Arrays.fill(nonce, (byte) 0); + if (challenge != null) { + Arrays.fill(challenge, (byte) 0); + } + if (signatureBytes != null) { + Arrays.fill(signatureBytes, (byte) 0); + } + } + } + + private static String fingerprint(BigInteger modulus, BigInteger exponent) { + String canonicalJwk = + "{\"e\":\"" + + base64Url(unsignedBytes(exponent)) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsignedBytes(modulus)) + + "\"}"; + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(canonicalJwk.getBytes(StandardCharsets.US_ASCII)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + private static byte[] unsignedBytes(BigInteger value) { + byte[] encoded = value.toByteArray(); + if (encoded.length > 1 && encoded[0] == 0) { + return Arrays.copyOfRange(encoded, 1, encoded.length); + } + return encoded; + } + + private static String base64Url(byte[] bytes) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static boolean positive(BigInteger value) { + return value != null && value.signum() > 0; + } + + private static InvalidMountedSignerBundleException invalid() { + return new InvalidMountedSignerBundleException(); + } + + /** Caller-supplied durable request identity; it is not authorization or proof of provisioning. */ + public record ExpectedIdentity( + String environmentId, + String clusterId, + String namespace, + String operationId, + String generation, + String kid, + String publicKeyFingerprint) {} + + /** Closed signing input built only from the issuance repository's locked owner readback. */ + record DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + Optional bound) { + DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot) { + this(identity, authoritySnapshot, Optional.empty()); + } + + DelegationSigningSpec { + Objects.requireNonNull(bound); + Objects.requireNonNull(identity, "Persisted pending identity is required"); + Objects.requireNonNull(authoritySnapshot, "Persisted Account authority is required"); + if (!authoritySnapshot.accountId().equals(identity.accountId()) + || identity.issuedAtEpochSecond() <= 0L + || identity.notBeforeEpochSecond() <= 0L + || identity.notBeforeEpochSecond() > identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() <= identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() - identity.issuedAtEpochSecond() + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid(); + } + } + } + + record BoundDelegationClaims( + String tenantId, Map authorityTuple, Map membershipVersion) { + BoundDelegationClaims { + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .requirePublicTenantBoundAuthority(tenantId, authorityTuple, membershipVersion); + authorityTuple = Map.copyOf(authorityTuple); + membershipVersion = Map.copyOf(membershipVersion); + } + } + + @FunctionalInterface + interface DelegationCandidateConsumer { + /** The caller persists the exact candidate before any internal transient handoff. */ + void bindExactCandidate(SignedDelegationDigest digest, byte[] compactJwt); + } + + /** Non-secret operation, signer and token-hash identity; never includes compact JWT bytes. */ + static final class SignedDelegationDigest { + private final UUID issuanceOperationId; + private final UUID requestId; + private final UUID jti; + private final String signerOperationId; + private final String signerGeneration; + private final String kid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedDelegationDigest( + UUID issuanceOperationId, + UUID requestId, + UUID jti, + String signerOperationId, + String signerGeneration, + String kid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.issuanceOperationId = Objects.requireNonNull(issuanceOperationId); + this.requestId = Objects.requireNonNull(requestId); + this.jti = Objects.requireNonNull(jti); + this.signerOperationId = Objects.requireNonNull(signerOperationId); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.kid = Objects.requireNonNull(kid); + this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + if (compactTokenSha256 == null || !FINGERPRINT.matcher(compactTokenSha256).matches()) { + throw invalid(); + } + this.compactTokenSha256 = compactTokenSha256; + } + + UUID issuanceOperationId() { + return issuanceOperationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + String signerOperationId() { + return signerOperationId; + } + + String signerGeneration() { + return signerGeneration; + } + + String kid() { + return kid; + } + + String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "SignedDelegationDigest[redacted]"; + } + } + + public enum ProbeKind { + CANARY, + REPRESENTATIVE + } + + @FunctionalInterface + interface ProbeDeliveryConsumer { + /** The caller must durably pin {@code digest} before passing the transient bytes onward. */ + void persistAttemptAndDeliver(SignedProbeDigest digest, byte[] compactJwt); + } + + /** A closed claim-shape input; its constructor permits only the two declared readiness forms. */ + record ReadinessProbeSigningSpec( + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) { + ReadinessProbeSigningSpec { + if (validatorId == null + || !READINESS_VALIDATOR_ID.equals(validatorId) + || probeKind == null + || jti == null + || jti.version() != 4 + || jti.variant() != 2 + || targetGeneration == null + || !GENERATION.matcher(targetGeneration).matches() + || targetKid == null + || !KID.matcher(targetKid).matches() + || issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw invalid(); + } + if (probeKind == ProbeKind.CANARY) { + if (!READINESS_CANARY_PROFILE.equals(tokenProfile) + || !READINESS_CANARY_AUDIENCE.equals(audience)) { + throw invalid(); + } + } else { + boolean exactProfileAudience = + (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)) + || (REPRESENTATIVE_PROFILE.equals(tokenProfile) + && REPRESENTATIVE_AUDIENCE.equals(audience)); + if (!exactProfileAudience) { + throw invalid(); + } + } + } + } + + /** Non-secret output from the one constrained signing operation; it never contains JWT bytes. */ + public static final class SignedProbeDigest { + private final String operationId; + private final String validatorId; + private final ProbeKind probeKind; + private final String tokenProfile; + private final String audience; + private final UUID jti; + private final String targetGeneration; + private final String targetKid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedProbeDigest( + String operationId, + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.operationId = operationId; + this.validatorId = validatorId; + this.probeKind = probeKind; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.jti = jti; + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.publicKeyFingerprint = publicKeyFingerprint; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.compactTokenSha256 = compactTokenSha256; + } + + public String operationId() { + return operationId; + } + + public String validatorId() { + return validatorId; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public UUID jti() { + return jti; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.SignedProbeDigest[operation=" + + operationId + + ", probeKind=" + + probeKind + + ", tokenBytes=discarded, authorization=none, verification=unproved]"; + } + } + + /** Non-secret, process-local observation with no token-signing or private-key accessor. */ + public static final class LocalObservation { + private final ExpectedIdentity expectedIdentity; + private final String publicKeyFingerprint; + + private LocalObservation(ExpectedIdentity expectedIdentity, String publicKeyFingerprint) { + this.expectedIdentity = expectedIdentity; + this.publicKeyFingerprint = publicKeyFingerprint; + } + + public ExpectedIdentity expectedIdentity() { + return expectedIdentity; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public boolean localPrivatePublicCorrespondenceObserved() { + return true; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.LocalObservation[local correspondence observed; " + + "authorization=none, provisioning=unproved, readiness=unproved]"; + } + } + + /** Safe generic failure for malformed, unavailable, or mismatched mounted projections. */ + public static final class InvalidMountedSignerBundleException extends IllegalArgumentException { + private InvalidMountedSignerBundleException() { + super("Mounted signer correspondence is unavailable or invalid"); + } + } + + private record ParsedPrivateBundle( + PrivateKey privateKey, + ExpectedIdentity identity, + BigInteger publicModulus, + BigInteger publicExponent) {} + + private record VerifiedMountedSigner( + LocalObservation observation, PrivateKey privateKey, RSAPublicKey publicKey) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql new file mode 100644 index 0000000000..49e6204d33 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql @@ -0,0 +1,777 @@ +-- V2 readiness plans bind every protected live validator Pod and retain one immutable production +-- verification receipt per Pod and logical probe. Existing V1 plans and receipts remain retained +-- and partial; they are never rewritten into V2 closure evidence. + +ALTER TABLE account_jwt_readiness_probe_plans + DROP CONSTRAINT account_jwt_readiness_plan_window_check; + +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version IN (1, 2) + AND (plan_version <> 2 OR inventory_snapshot_digest IS NOT NULL)); + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN entry_plan_version SMALLINT NOT NULL DEFAULT 1; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_count SMALLINT; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_closure_sha256 VARCHAR(64); + +ALTER TABLE account_jwt_readiness_probe_entries + DROP CONSTRAINT account_jwt_readiness_probe_evidence_check; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_plan_version IN (1, 2) + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL + OR (entry_plan_version = 1 AND verification_receipt_version = 1) + OR (entry_plan_version = 2 AND verification_receipt_version = 2)) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND (pod_receipt_count IS NULL OR pod_receipt_count BETWEEN 1 AND 256) + AND (pod_receipt_closure_sha256 IS NULL + OR pod_receipt_closure_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND entry_plan_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 2 + AND entry_plan_version = 2 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid = target_kid + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NOT NULL + AND pod_receipt_closure_sha256 = verification_receipt_sha256)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)); + +CREATE TABLE account_jwt_readiness_validator_pods ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL, + inventory_snapshot_digest VARCHAR(64) NOT NULL, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + deployment_uid UUID NOT NULL, + pod_uid UUID NOT NULL, + pod_ip VARCHAR(45) NOT NULL, + image VARCHAR(512) NOT NULL, + verifier_config_sha256 VARCHAR(64) NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + expected_outcome VARCHAR(32) NOT NULL, + exact_pod_endpoint VARCHAR(512) NOT NULL, + canonical_service_uri VARCHAR(256) NOT NULL, + expected_pod_leaf_spki_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_validator_pod_entry_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind) + REFERENCES account_jwt_readiness_probe_entries( + rotation_operation_id, validator_id, token_profile, audience, probe_kind) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND plan_digest ~ '^[0-9a-f]{64}$' + AND inventory_snapshot_digest ~ '^[0-9a-f]{64}$' + AND validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND deployment_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND pod_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND (pod_ip ~ '^(?:[0-9]{1,3}[.]){3}[0-9]{1,3}$' OR pod_ip ~ '^[0-9a-f:]+$') + AND image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND expected_outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND exact_pod_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND canonical_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND expected_pod_leaf_spki_sha256 ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_readiness_pod_receipts ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + pod_uid UUID NOT NULL, + receipt_version SMALLINT NOT NULL, + jti UUID NOT NULL, + source_entry_version BIGINT NOT NULL, + compact_token_sha256 VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + outcome VARCHAR(32) NOT NULL, + observed_pod_uid UUID NOT NULL, + observed_image VARCHAR(512) NOT NULL, + observed_verifier_config_sha256 VARCHAR(64) NOT NULL, + verified_kid VARCHAR(64), + receiver_endpoint VARCHAR(512) NOT NULL, + receiver_service_uri VARCHAR(256) NOT NULL, + receiver_peer_spki_sha256 VARCHAR(64) NOT NULL, + observed_at_epoch_seconds BIGINT NOT NULL, + receipt_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_pod_receipt_target_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + REFERENCES account_jwt_readiness_validator_pods( + rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_pod_receipt_shape_check + CHECK (receipt_version = 1 + AND source_entry_version > 0 + AND compact_token_sha256 ~ '^[0-9a-f]{64}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND observed_pod_uid = pod_uid + AND observed_image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND observed_verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND receiver_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND receiver_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND receiver_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND observed_at_epoch_seconds > 0 + AND receipt_sha256 ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; + account_profiles jsonb; + game_session_profiles jsonb; +BEGIN + matrix := NEW.applicability_matrix_json::jsonb; + IF NEW.plan_version = 1 THEN + IF NEW.validator_inventory_complete + OR matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Legacy readiness plans remain explicitly partial and Account-only' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.plan_version <> 2 + OR NEW.inventory_snapshot_digest IS NULL + OR matrix ->> 'schemaVersion' <> '2' + OR matrix ->> 'inventorySnapshotDigest' IS DISTINCT FROM NEW.inventory_snapshot_digest + OR jsonb_array_length(matrix -> 'validators') < 1 + OR jsonb_array_length(matrix -> 'validators') > 32 + OR jsonb_array_length(matrix -> 'productionProfiles') <> 3 THEN + RAISE EXCEPTION 'Readiness V2 plan must bind its protected live snapshot and closed profile family' + USING ERRCODE = '23514'; + END IF; + IF NEW.validator_inventory_complete THEN + SELECT value -> 'applicableProfiles' INTO account_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'account-service'; + SELECT value -> 'applicableProfiles' INTO game_session_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'game-session-service'; + IF matrix ->> 'inventoryStatus' <> 'PROTECTED_LIVE_COMPLETE' + OR jsonb_array_length(matrix -> 'validators') <> 2 + OR account_profiles IS NULL + OR jsonb_array_length(account_profiles) <> 3 + OR NOT (account_profiles @> '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) + OR game_session_profiles IS NULL + OR jsonb_array_length(game_session_profiles) <> 1 + OR NOT (game_session_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness V2 completion requires exact Account and Game Session profile inventory' + USING ERRCODE = '23514'; + END IF; + ELSIF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' THEN + RAISE EXCEPTION 'Incomplete Readiness V2 inventory must remain explicitly partial' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_readiness_entry_plan_version_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.entry_plan_version IS DISTINCT FROM OLD.entry_plan_version THEN + RAISE EXCEPTION 'Readiness entry schema version is immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR NEW.entry_plan_version IS DISTINCT FROM plan_row.plan_version THEN + RAISE EXCEPTION 'Readiness entry schema differs from its immutable plan' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_plan_version_binding + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_plan_version_guard(); + +DROP TRIGGER account_jwt_readiness_entry_lifecycle ON account_jwt_readiness_probe_entries; +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v1 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 1) + EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +CREATE TRIGGER account_jwt_readiness_entry_delete_guard + BEFORE DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_expected_pod_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + snapshot_json jsonb; + validator_json jsonb; + pod_json jsonb; + expected_outcome_value text; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Expected readiness Pod bindings are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = NEW.inventory_snapshot_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 OR entry_row.entry_plan_version <> 2 + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR plan_row.inventory_snapshot_digest IS DISTINCT FROM NEW.inventory_snapshot_digest + OR plan_row.applicability_matrix_digest IS DISTINCT FROM NEW.applicability_matrix_digest + OR (plan_row.environment_id, plan_row.cluster_id, plan_row.kubernetes_namespace, + plan_row.expected_cluster_incarnation_uid, plan_row.expected_namespace_uid) + IS DISTINCT FROM (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.cluster_incarnation_uid, NEW.namespace_uid) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'pods') AS pod(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND validator.value ->> 'deploymentUid' = NEW.deployment_uid::text + AND pod.value ->> 'uid' = NEW.pod_uid::text + AND pod.value ->> 'podIp' = NEW.pod_ip + AND pod.value ->> 'exactPodEndpoint' = NEW.exact_pod_endpoint + AND pod.value ->> 'canonicalServiceUri' = NEW.canonical_service_uri + AND pod.value ->> 'leafSpkiSha256' = NEW.expected_pod_leaf_spki_sha256 + AND pod.value ->> 'image' = NEW.image + AND pod.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256 + AND validator.value ->> 'image' = NEW.image + AND validator.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256) + OR (NEW.probe_kind = 'CANARY' AND NEW.expected_outcome <> 'ACCEPT') + OR (NEW.probe_kind = 'REPRESENTATIVE' AND ( + (NEW.expected_outcome = 'ACCEPT') IS DISTINCT FROM EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'profiles') AS profile(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND profile.value ->> 'tokenProfile' = NEW.token_profile + AND profile.value ->> 'audience' = NEW.audience))) THEN + RAISE EXCEPTION 'Expected readiness Pod differs from its exact protected inventory and entry' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_expected_pod_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_validator_pods + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_expected_pod_guard(); + +CREATE FUNCTION account_jwt_readiness_pod_receipt_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + pod_row account_jwt_readiness_validator_pods%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Readiness Pod verification receipts are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + FOR UPDATE; + SELECT * INTO pod_row + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + AND pod_uid = NEW.pod_uid + FOR KEY SHARE; + IF plan_row.plan_version <> 2 OR plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR entry_row.entry_plan_version <> 2 OR entry_row.state <> 'ISSUED' + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR entry_row.entry_version IS DISTINCT FROM NEW.source_entry_version + OR entry_row.compact_token_sha256 IS DISTINCT FROM NEW.compact_token_sha256 + OR entry_row.target_generation IS DISTINCT FROM NEW.target_generation + OR entry_row.target_kid IS DISTINCT FROM NEW.target_kid + OR entry_row.expected_active_generation IS DISTINCT FROM NEW.expected_active_generation + OR entry_row.expected_active_kid IS DISTINCT FROM NEW.expected_active_kid + OR pod_row.expected_outcome IS DISTINCT FROM NEW.outcome + OR pod_row.exact_pod_endpoint IS NULL + OR pod_row.exact_pod_endpoint IS DISTINCT FROM NEW.receiver_endpoint + OR pod_row.canonical_service_uri IS DISTINCT FROM NEW.receiver_service_uri + OR pod_row.expected_pod_leaf_spki_sha256 IS DISTINCT FROM NEW.receiver_peer_spki_sha256 + OR pod_row.pod_uid IS DISTINCT FROM NEW.observed_pod_uid + OR pod_row.image IS DISTINCT FROM NEW.observed_image + OR pod_row.verifier_config_sha256 IS DISTINCT FROM NEW.observed_verifier_config_sha256 + OR NEW.verified_kid IS DISTINCT FROM NEW.target_kid + OR NEW.observed_at_epoch_seconds < entry_row.planned_issued_at_epoch_seconds + OR NEW.observed_at_epoch_seconds >= entry_row.expires_at_epoch_seconds + OR NEW.observed_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT + OR CURRENT_TIMESTAMP < to_timestamp(entry_row.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(entry_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Readiness Pod receipt differs from exact current inventory, probe, or TLS identity' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_pod_receipt_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_pod_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_pod_receipt_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_pod_count integer; + receipt_count integer; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 + OR NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.registry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Readiness V2 entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' + OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id) THEN + RAISE EXCEPTION 'Readiness V2 canary entry is outside the closed validator set' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS p(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id + AND p.value ->> 'tokenProfile' = NEW.token_profile + AND p.value ->> 'audience' = NEW.audience) THEN + RAISE EXCEPTION 'Readiness V2 representative entry is outside its exact profile matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + IF OLD.entry_plan_version <> 2 OR NEW.entry_plan_version <> 2 + OR NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds + OR NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Readiness V2 entry identity/version is immutable except for one exact transition' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT count(*) INTO expected_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT count(*) INTO receipt_count + FROM account_jwt_readiness_pod_receipts + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + IF expected_pod_count <= 0 OR expected_pod_count <> receipt_count + OR NEW.verification_receipt_version IS DISTINCT FROM 2 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.verification_receipt_sha256 IS NULL + OR NEW.pod_receipt_count IS DISTINCT FROM expected_pod_count + OR NEW.pod_receipt_closure_sha256 IS DISTINCT FROM NEW.verification_receipt_sha256 + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_instance_id IS NULL + OR NEW.validator_binding_digest IS NULL + OR NEW.validator_config_revision IS NULL + OR NEW.validator_peer_uri IS NULL + OR NEW.validator_peer_spki_sha256 IS NULL + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Readiness V2 VERIFIED transition lacks complete exact per-Pod receipts' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('ABORTED', 'EXPIRED') AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account JWT readiness V2 lifecycle transition is unavailable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v2 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 2) + EXECUTE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_inventory_plan_closure_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + operation_id UUID; + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; + expected_pod_count integer; + actual_pod_count integer; +BEGIN + operation_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.rotation_operation_id ELSE NEW.rotation_operation_id END; + SELECT * INTO plan_row FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = operation_id; + IF NOT FOUND OR plan_row.plan_version <> 2 THEN + RETURN NULL; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF snapshot_json IS NULL THEN + RAISE EXCEPTION 'Readiness V2 inventory snapshot is missing' USING ERRCODE = '23514'; + END IF; + SELECT count(*) * 4 INTO expected_entry_count + FROM jsonb_array_elements(snapshot_json -> 'validators'); + SELECT count(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + SELECT COALESCE(sum(jsonb_array_length(validator.value -> 'pods') * 4), 0) + INTO expected_pod_count + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value); + SELECT count(*) INTO actual_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + IF actual_entry_count <> expected_entry_count + OR actual_pod_count <> expected_pod_count + OR actual_entry_count > 256 OR actual_pod_count > 256 + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS profile(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = profile.value ->> 'tokenProfile' + AND entry.audience = profile.value ->> 'audience' + AND entry.probe_kind = 'REPRESENTATIVE')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = 'account-jwt-readiness-canary' + AND entry.audience = 'firemud-account-jwt-readiness' + AND entry.probe_kind = 'CANARY')) + OR EXISTS ( + SELECT 1 + FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND (SELECT count(*) FROM account_jwt_readiness_validator_pods target + WHERE target.rotation_operation_id = entry.rotation_operation_id + AND target.validator_id = entry.validator_id + AND target.token_profile = entry.token_profile + AND target.audience = entry.audience + AND target.probe_kind = entry.probe_kind) + <> (SELECT jsonb_array_length(validator.value -> 'pods') + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' = entry.validator_id)) THEN + RAISE EXCEPTION 'Readiness V2 plan is missing a validator entry or exact per-Pod inventory row' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_jwt_readiness_plan_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_plans + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_entry_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_entries + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_pod_v2_closure + AFTER INSERT ON account_jwt_readiness_validator_pods + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql new file mode 100644 index 0000000000..ceb2aa436f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql @@ -0,0 +1,126 @@ +-- Correct the promotion insert guard's receipt source without adding a duplicate promotion-row +-- field. The immutable readiness plan already binds the generation receipt digest. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_generation_receipt_digest VARCHAR(64); + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT generation_receipt_digest, validator_inventory_complete, expires_at_epoch_seconds + INTO plan_generation_receipt_digest, plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_generation_receipt_digest IS DISTINCT FROM result_row.receipt_digest + OR plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql new file mode 100644 index 0000000000..1e71c085a5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql @@ -0,0 +1,405 @@ +-- Account-owned signer desired state, Account-selected generation requests, and a dormant +-- PREPARED schema for the later lifecycle phase. Generation/materialization evidence is not a +-- PREPARED promotion record and never authorizes signing. +CREATE TABLE account_jwt_signer_desired_states ( + environment_id VARCHAR(63) PRIMARY KEY, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL DEFAULT 'jwt-signing-keys', + public_jwks_config_map_name VARCHAR(63) NOT NULL DEFAULT 'jwt-jwks', + record_version BIGINT NOT NULL DEFAULT 1, + durable_active_generation BIGINT, + durable_active_kid VARCHAR(128), + published_active_generation BIGINT, + published_active_kid VARCHAR(128), + generation_operation_id UUID, + prepared_operation_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_state_binding_unique + UNIQUE (environment_id, cluster_id, kubernetes_namespace, custody_mode), + CONSTRAINT account_jwt_signer_state_environment_check + CHECK (environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_state_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_state_resource_names_check + CHECK (private_secret_name = 'jwt-signing-keys' + AND public_jwks_config_map_name = 'jwt-jwks'), + CONSTRAINT account_jwt_signer_state_version_check CHECK (record_version > 0), + CONSTRAINT account_jwt_signer_state_durable_active_shape_check + CHECK ((durable_active_generation IS NULL AND durable_active_kid IS NULL) + OR (durable_active_generation IS NOT NULL + AND durable_active_generation > 0 + AND durable_active_kid IS NOT NULL + AND durable_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_state_published_active_shape_check + CHECK ((published_active_generation IS NULL AND published_active_kid IS NULL) + OR (published_active_generation IS NOT NULL + AND published_active_generation > 0 + AND published_active_kid IS NOT NULL + AND published_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) +); + +CREATE TABLE account_jwt_signer_promotion_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(128) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_private_secret_resource_version VARCHAR(256) NOT NULL, + expected_public_jwks_resource_version VARCHAR(256) NOT NULL, + expected_public_active_generation BIGINT, + expected_public_active_kid VARCHAR(128), + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PREPARED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_promotion_operation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_promotion_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_promotion_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_promotion_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_promotion_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_record_version_check + CHECK (expected_record_version > 0 + AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_promotion_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL + AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (expected_previous_generation IS NOT NULL + AND target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_promotion_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_promotion_fingerprint_check + CHECK (target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_resource_versions_check + CHECK (expected_private_secret_resource_version ~ '^[!-~]+$' + AND char_length(expected_private_secret_resource_version) BETWEEN 1 AND 256 + AND expected_public_jwks_resource_version ~ '^[!-~]+$' + AND char_length(expected_public_jwks_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_signer_promotion_public_active_shape_check + CHECK ((expected_public_active_generation IS NULL AND expected_public_active_kid IS NULL) + OR (expected_public_active_generation IS NOT NULL + AND expected_public_active_generation > 0 + AND expected_public_active_kid IS NOT NULL + AND expected_public_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_published_generation_check + CHECK (expected_public_active_generation IS NULL + OR (target_generation > expected_public_active_generation + AND target_kid <> expected_public_active_kid)), + CONSTRAINT account_jwt_signer_promotion_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_promotion_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea), + CONSTRAINT account_jwt_signer_promotion_status_check CHECK (status = 'PREPARED') +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_prepared_operation_fk + FOREIGN KEY (prepared_operation_id) + REFERENCES account_jwt_signer_promotion_operations(operation_id) + ON DELETE RESTRICT; + +CREATE TABLE account_jwt_signer_generation_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, target_generation, target_kid, + expected_published_generation, expected_published_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_observation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_receipt_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_generation_binding_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_generation_digest_check + CHECK (operation_digest_version = 1 AND operation_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_state_version_check + CHECK (expected_record_version > 0 AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_generation_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_generation_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_generation_published_shape_check + CHECK ((expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_published_generation IS NOT NULL AND expected_published_generation > 0 + AND expected_published_kid IS NOT NULL + AND expected_published_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_trust_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_generation_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_generation_operation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT; + +CREATE UNIQUE INDEX account_jwt_signer_generation_target_once + ON account_jwt_signer_generation_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_generation_kid_once + ON account_jwt_signer_generation_operations (environment_id, target_kid); + +CREATE UNIQUE INDEX account_jwt_signer_one_prepared_operation_per_environment + ON account_jwt_signer_promotion_operations (environment_id) + WHERE status = 'PREPARED'; + +CREATE UNIQUE INDEX account_jwt_signer_target_generation_once + ON account_jwt_signer_promotion_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_target_kid_once + ON account_jwt_signer_promotion_operations (environment_id, target_kid); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_environment VARCHAR(63); + operation_expected_version BIGINT; + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + operation_status VARCHAR(16); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.environment_id IS DISTINCT FROM OLD.environment_id + OR NEW.cluster_id IS DISTINCT FROM OLD.cluster_id + OR NEW.kubernetes_namespace IS DISTINCT FROM OLD.kubernetes_namespace + OR NEW.custody_mode IS DISTINCT FROM OLD.custody_mode + OR NEW.private_secret_name IS DISTINCT FROM OLD.private_secret_name + OR NEW.public_jwks_config_map_name IS DISTINCT FROM OLD.public_jwks_config_map_name + OR NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.prepared_operation_id IS DISTINCT FROM OLD.prepared_operation_id THEN + RAISE EXCEPTION 'JWT signer promotion prerequisites are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + + IF OLD.generation_operation_id IS NOT NULL + OR NEW.generation_operation_id IS NULL + OR OLD.prepared_operation_id IS NOT NULL + OR NEW.prepared_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT signer generation operation is already fenced or not promotable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + + SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, + expected_record_version, expected_previous_generation, expected_previous_kid, + expected_published_generation, expected_published_kid, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_expected_version, operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid, + operation_target_generation, operation_target_kid, operation_algorithm, + operation_cluster_uid, operation_namespace_uid, + operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id; + IF operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_expected_version IS DISTINCT FROM OLD.record_version + OR operation_previous_generation IS DISTINCT FROM OLD.durable_active_generation + OR operation_previous_kid IS DISTINCT FROM OLD.durable_active_kid + OR operation_published_generation IS DISTINCT FROM OLD.published_active_generation + OR operation_published_kid IS DISTINCT FROM OLD.published_active_kid + OR operation_algorithm IS DISTINCT FROM 'RS256' + OR operation_cluster_uid IS NULL OR operation_namespace_uid IS NULL + OR operation_trust_digest IS NULL OR operation_trust_revision IS NULL THEN + RAISE EXCEPTION 'Account JWT signer state must point to its exact owner-selected generation operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_desired_state_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer desired state cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history is immutable and PREPARED-only' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_operation_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation operation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_desired_state_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_desired_states + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_desired_state_guard(); + +CREATE TRIGGER account_jwt_signer_desired_state_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_desired_states + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_desired_state_no_truncate(); + +CREATE TRIGGER account_jwt_signer_operation_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_operation_guard(); + +CREATE TRIGGER account_jwt_signer_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_operation_no_truncate(); + +CREATE TRIGGER account_jwt_signer_generation_operation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql new file mode 100644 index 0000000000..baab6841bd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql @@ -0,0 +1,327 @@ +-- Immutable Account-bound reports for the fixed private Secret. The first report observes only +-- the fixed-name pre-created Secret; the second records one pending-key generation/CAS result. +-- Neither report changes active state, PREPARED state, JWKS, token signing, or readiness. +CREATE TABLE account_jwt_signer_secret_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + observation_digest_version SMALLINT NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_observation_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, expected_record_version, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_readback_unique + UNIQUE (operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version), + CONSTRAINT account_jwt_signer_observation_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_observation_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_observation_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_observation_version_check + CHECK (expected_record_version > 0 AND operation_digest_version = 1 + AND observation_digest_version = 1), + CONSTRAINT account_jwt_signer_observation_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_observation_resource_version_check + CHECK (observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256) +); + +CREATE TABLE account_jwt_signer_generation_results ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + expected_prior_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + public_jwk_json VARCHAR(8192) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_result_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, + target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_observation_fk + FOREIGN KEY (operation_id, operation_digest, generation_request_digest, + secret_uid, expected_prior_resource_version) + REFERENCES account_jwt_signer_secret_observations( + operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_generation_result_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_generation_result_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_result_version_check + CHECK (desired_state_version > 1), + CONSTRAINT account_jwt_signer_generation_result_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_result_resource_versions_check + CHECK (expected_prior_resource_version ~ '^[!-~]+$' + AND char_length(expected_prior_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_prior_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_signer_generation_result_key_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND target_algorithm = 'RS256' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +ALTER TABLE account_jwt_signer_generation_results + ADD CONSTRAINT account_jwt_signer_generation_result_public_jwk_check + CHECK (octet_length(public_jwk_json) <= 8192 + AND jsonb_typeof(public_jwk_json::jsonb) = 'object' + AND (public_jwk_json::jsonb ?& ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e']) + AND NOT (public_jwk_json::jsonb ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k']) + AND public_jwk_json::jsonb - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] = '{}'::jsonb); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_secret_observation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS DISTINCT FROM NEW.expected_record_version + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer Secret observation must bind the current Account operation and trust' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_secret_observation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_result_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_generation BIGINT; + operation_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + observation_generation_request_digest VARCHAR(64); + observation_secret_uid UUID; + observation_resource_version VARCHAR(256); +BEGIN + -- Lock order matches every Account repository write: desired state, then operation. + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.target_generation, generation_op.target_kid, + generation_op.target_algorithm, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_generation, + operation_kid, operation_algorithm, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + SELECT observation.generation_request_digest, observation.secret_uid, + observation.observed_resource_version + INTO observation_generation_request_digest, observation_secret_uid, + observation_resource_version + FROM account_jwt_signer_secret_observations AS observation + WHERE observation.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR NEW.desired_state_version IS DISTINCT FROM state_record_version + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS NULL + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_generation IS DISTINCT FROM NEW.target_generation + OR operation_kid IS DISTINCT FROM NEW.target_kid + OR operation_algorithm IS DISTINCT FROM NEW.target_algorithm + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR observation_generation_request_digest IS DISTINCT FROM NEW.generation_request_digest + OR observation_secret_uid IS DISTINCT FROM NEW.secret_uid + OR observation_resource_version IS DISTINCT FROM NEW.expected_prior_resource_version + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer generation result must bind the exact current request and observation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_result_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_evidence_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_evidence_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_secret_observation_guard + BEFORE INSERT ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_secret_observation_guard(); + +CREATE TRIGGER account_jwt_signer_secret_observation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_secret_observation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_secret_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_guard + BEFORE INSERT ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_result_guard(); + +CREATE TRIGGER account_jwt_signer_generation_result_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_results + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql new file mode 100644 index 0000000000..3914eef34d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql @@ -0,0 +1,600 @@ +-- Account records its exact public-JWKS intent before the protected ConfigMap CAS, then binds +-- server readback and local mounted correspondence to the same current generation operation. +-- These observations are non-authorizing and never advance signer lifecycle state. +CREATE TABLE account_jwt_jwks_prepublication_intents ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + api_config_revision VARCHAR(128) NOT NULL, + config_map_name VARCHAR(63) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + expected_snapshot_digest VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + expected_durable_active_json VARCHAR(512) NOT NULL, + expected_published_active_json VARCHAR(512) NOT NULL, + jwks_json TEXT NOT NULL, + generation_marker_json TEXT NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_intent_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_generation_result_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_digest_unique + UNIQUE (operation_id, intent_digest), + CONSTRAINT account_jwt_jwks_intent_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_name = 'jwt-jwks' + AND desired_state_version > 1 + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]+$' + AND char_length(target_kid) BETWEEN 1 AND 64), + CONSTRAINT account_jwt_jwks_intent_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_jwks_intent_resource_version_check + CHECK (expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_jwks_intent_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND expected_snapshot_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND intent_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_jwks_intent_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(trust_config_revision) BETWEEN 1 AND 128 + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(api_config_revision) BETWEEN 1 AND 128), + CONSTRAINT account_jwt_jwks_intent_content_bounds_check + CHECK (octet_length(jwks_json) BETWEEN 1 AND 262144 + AND octet_length(generation_marker_json) BETWEEN 1 AND 16384 + AND octet_length(expected_durable_active_json) BETWEEN 1 AND 512 + AND octet_length(expected_published_active_json) BETWEEN 1 AND 512) +); + +CREATE TABLE account_jwt_jwks_publication_receipts ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_receipt_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_intent_fk + FOREIGN KEY (operation_id, intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_digest_unique + UNIQUE (operation_id, intent_digest, receipt_digest), + CONSTRAINT account_jwt_jwks_receipt_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_jwks_receipt_digest_check + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_jwks_mount_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_mount_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_receipt_fk + FOREIGN KEY (operation_id, intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_digest_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$') +); + +-- Keep the trigger bodies out of jOOQ DDL parsing; the database still enforces these invariants. +-- [jooq ignore start] +CREATE FUNCTION account_jwt_jwks_lock_current_generation( + p_operation_id UUID, + p_environment_id VARCHAR, + p_cluster_id VARCHAR, + p_namespace VARCHAR, + p_custody_mode VARCHAR, + p_operation_digest VARCHAR, + p_generation_request_digest VARCHAR, + p_generation_receipt_digest VARCHAR, + p_desired_state_version BIGINT, + p_cluster_uid UUID, + p_namespace_uid UUID, + p_trust_binding_digest VARCHAR, + p_trust_config_revision VARCHAR, + p_target_generation BIGINT, + p_target_kid VARCHAR, + p_public_key_fingerprint VARCHAR +) +RETURNS JSONB +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_version BIGINT; + state_prepared_operation_id UUID; + durable_active JSONB; + published_active JSONB; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_target_algorithm VARCHAR(16); + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + result_environment VARCHAR(63); + result_cluster VARCHAR(128); + result_namespace VARCHAR(63); + result_mode VARCHAR(64); + result_operation_digest VARCHAR(64); + result_generation_request_digest VARCHAR(64); + result_desired_state_version BIGINT; + result_cluster_uid UUID; + result_namespace_uid UUID; + result_trust_digest VARCHAR(64); + result_trust_revision VARCHAR(128); + result_generation BIGINT; + result_kid VARCHAR(64); + result_fingerprint VARCHAR(64); + result_receipt_digest VARCHAR(64); + result_jwk VARCHAR(8192); +BEGIN + SELECT desired_state.generation_operation_id, + desired_state.record_version, + desired_state.prepared_operation_id, + CASE WHEN desired_state.durable_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.durable_active_generation::text, + 'kid', desired_state.durable_active_kid) + END, + CASE WHEN desired_state.published_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.published_active_generation::text, + 'kid', desired_state.published_active_kid) + END + INTO state_operation_id, state_version, state_prepared_operation_id, + durable_active, published_active + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = p_environment_id + AND desired_state.cluster_id = p_cluster_id + AND desired_state.kubernetes_namespace = p_namespace + AND desired_state.custody_mode = p_custody_mode + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS current desired state is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_op.environment_id, generation_op.cluster_id, + generation_op.kubernetes_namespace, generation_op.custody_mode, + generation_op.operation_digest, generation_op.expected_record_version, + generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision, generation_op.target_generation, + generation_op.target_kid, generation_op.target_algorithm, + generation_op.expected_previous_generation, generation_op.expected_previous_kid, + generation_op.expected_published_generation, generation_op.expected_published_kid + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_digest, operation_expected_version, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision, + operation_target_generation, operation_target_kid, operation_target_algorithm, + operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS generation operation is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_result.environment_id, generation_result.cluster_id, + generation_result.kubernetes_namespace, generation_result.custody_mode, + generation_result.operation_digest, generation_result.generation_request_digest, + generation_result.desired_state_version, + generation_result.expected_cluster_incarnation_uid, + generation_result.expected_namespace_uid, generation_result.trust_binding_digest, + generation_result.trust_config_revision, generation_result.target_generation, + generation_result.target_kid, generation_result.public_key_fingerprint, + generation_result.receipt_digest, generation_result.public_jwk_json + INTO result_environment, result_cluster, result_namespace, result_mode, + result_operation_digest, result_generation_request_digest, result_desired_state_version, + result_cluster_uid, result_namespace_uid, result_trust_digest, result_trust_revision, + result_generation, result_kid, result_fingerprint, result_receipt_digest, result_jwk + FROM account_jwt_signer_generation_results AS generation_result + WHERE generation_result.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND + OR state_operation_id IS DISTINCT FROM p_operation_id + OR state_version IS DISTINCT FROM p_desired_state_version + OR state_prepared_operation_id IS NOT NULL + OR operation_environment IS DISTINCT FROM p_environment_id + OR operation_cluster IS DISTINCT FROM p_cluster_id + OR operation_namespace IS DISTINCT FROM p_namespace + OR operation_mode IS DISTINCT FROM p_custody_mode + OR operation_digest IS DISTINCT FROM p_operation_digest + OR operation_expected_version + 1 IS DISTINCT FROM p_desired_state_version + OR operation_cluster_uid IS DISTINCT FROM p_cluster_uid + OR operation_namespace_uid IS DISTINCT FROM p_namespace_uid + OR operation_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM p_trust_config_revision + OR operation_target_generation IS DISTINCT FROM p_target_generation + OR operation_target_kid IS DISTINCT FROM p_target_kid + OR operation_target_algorithm IS DISTINCT FROM 'RS256' + OR result_environment IS DISTINCT FROM p_environment_id + OR result_cluster IS DISTINCT FROM p_cluster_id + OR result_namespace IS DISTINCT FROM p_namespace + OR result_mode IS DISTINCT FROM p_custody_mode + OR result_operation_digest IS DISTINCT FROM p_operation_digest + OR result_generation_request_digest IS DISTINCT FROM p_generation_request_digest + OR result_receipt_digest IS DISTINCT FROM p_generation_receipt_digest + OR result_desired_state_version IS DISTINCT FROM p_desired_state_version + OR result_cluster_uid IS DISTINCT FROM p_cluster_uid + OR result_namespace_uid IS DISTINCT FROM p_namespace_uid + OR result_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR result_trust_revision IS DISTINCT FROM p_trust_config_revision + OR result_generation IS DISTINCT FROM p_target_generation + OR result_kid IS DISTINCT FROM p_target_kid + OR result_fingerprint IS DISTINCT FROM p_public_key_fingerprint + OR operation_previous_generation IS DISTINCT FROM + NULLIF(durable_active->>'generation', '')::BIGINT + OR operation_previous_kid IS DISTINCT FROM NULLIF(durable_active->>'kid', '') + OR operation_published_generation IS DISTINCT FROM + NULLIF(published_active->>'generation', '')::BIGINT + OR operation_published_kid IS DISTINCT FROM NULLIF(published_active->>'kid', '') THEN + RAISE EXCEPTION 'Account JWT JWKS evidence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + + RETURN jsonb_build_object( + 'durableActive', durable_active, + 'publishedActive', published_active, + 'publicJwk', result_jwk::jsonb); +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_public_intent() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_evidence JSONB; + jwks_document JSONB; + marker_document JSONB; + key_document JSONB; + key_kid TEXT; + seen_kids TEXT[] := ARRAY[]::TEXT[]; + target_key_count INTEGER := 0; + public_jwk JSONB; +BEGIN + current_evidence := account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.operation_digest, NEW.generation_request_digest, + NEW.generation_receipt_digest, NEW.desired_state_version, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision, + NEW.target_generation, NEW.target_kid, NEW.public_key_fingerprint); + + IF NEW.expected_durable_active_json::jsonb IS DISTINCT FROM current_evidence->'durableActive' + OR NEW.expected_published_active_json::jsonb IS DISTINCT FROM current_evidence->'publishedActive' THEN + RAISE EXCEPTION 'Account JWT JWKS active fence is stale' USING ERRCODE = '23514'; + END IF; + + jwks_document := NEW.jwks_json::jsonb; + IF jsonb_typeof(jwks_document) IS DISTINCT FROM 'object' + OR jwks_document - ARRAY['keys'] <> '{}'::jsonb + OR jsonb_typeof(jwks_document->'keys') IS DISTINCT FROM 'array' + OR jsonb_array_length(jwks_document->'keys') < 1 + OR jsonb_array_length(jwks_document->'keys') > 64 THEN + RAISE EXCEPTION 'Account public JWKS has an unsupported shape' USING ERRCODE = '23514'; + END IF; + public_jwk := current_evidence->'publicJwk'; + FOR key_document IN + SELECT jwks_key.value + FROM jsonb_array_elements(jwks_document->'keys') AS jwks_key(value) + LOOP + IF jsonb_typeof(key_document) IS DISTINCT FROM 'object' + OR key_document - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(key_document)) NOT BETWEEN 6 AND 7 + OR key_document ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] + OR key_document->>'kty' IS DISTINCT FROM 'RSA' + OR key_document->>'use' IS DISTINCT FROM 'sig' + OR key_document->>'alg' IS DISTINCT FROM 'RS256' + OR key_document->>'kid' IS NULL + OR key_document->>'kid' !~ '^[A-Za-z0-9_-]{1,64}$' + OR jsonb_typeof(key_document->'n') IS DISTINCT FROM 'string' + OR jsonb_typeof(key_document->'e') IS DISTINCT FROM 'string' + OR key_document->>'n' !~ '^[A-Za-z0-9_-]+$' + OR key_document->>'e' !~ '^[A-Za-z0-9_-]+$' + OR (key_document ? 'key_ops' + AND (jsonb_typeof(key_document->'key_ops') IS DISTINCT FROM 'array' + OR key_document->'key_ops' <> '["verify"]'::jsonb)) THEN + RAISE EXCEPTION 'Account public JWKS contains an invalid or private key' USING ERRCODE = '23514'; + END IF; + key_kid := key_document->>'kid'; + IF key_kid = ANY(seen_kids) THEN + RAISE EXCEPTION 'Account public JWKS has duplicate kids' USING ERRCODE = '23514'; + END IF; + seen_kids := array_append(seen_kids, key_kid); + IF key_kid = NEW.target_kid THEN + target_key_count := target_key_count + 1; + IF key_document IS DISTINCT FROM public_jwk THEN + RAISE EXCEPTION 'Account public JWKS pending key differs from receipt' USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + IF target_key_count <> 1 THEN + RAISE EXCEPTION 'Account public JWKS does not contain exactly one pending key' USING ERRCODE = '23514'; + END IF; + + marker_document := NEW.generation_marker_json::jsonb; + IF jsonb_typeof(marker_document) IS DISTINCT FROM 'object' + OR (marker_document - ARRAY['schemaVersion', 'phase', 'operationId', 'operationDigest', + 'generationRequestDigest', 'generationReceiptDigest', 'binding', 'publicConfigMap', + 'expectedDurableActive', 'expectedPublishedActive', 'pending']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(marker_document)) <> 11 + OR jsonb_typeof((marker_document -> 'binding')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'binding') - ARRAY['environmentId', 'clusterId', 'namespace', + 'expectedClusterIncarnationUid', 'expectedNamespaceUid', 'trustBindingDigest', + 'trustConfigRevision', 'apiBindingDigest', 'apiConfigRevision']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'binding'))) <> 9 + OR jsonb_typeof((marker_document -> 'publicConfigMap')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'publicConfigMap') - ARRAY['name']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'publicConfigMap'))) <> 1 + OR jsonb_typeof((marker_document -> 'pending')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'pending') - ARRAY['generation', 'kid', 'algorithm', + 'publicKeyFingerprint']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'pending'))) <> 4 + OR (marker_document ->> 'schemaVersion') IS DISTINCT FROM '1' + OR (marker_document ->> 'phase') IS DISTINCT FROM 'PREPUBLISHED' + OR (marker_document ->> 'operationId') IS DISTINCT FROM NEW.operation_id::TEXT + OR (marker_document ->> 'operationDigest') IS DISTINCT FROM NEW.operation_digest + OR (marker_document ->> 'generationRequestDigest') IS DISTINCT FROM NEW.generation_request_digest + OR (marker_document ->> 'generationReceiptDigest') IS DISTINCT FROM NEW.generation_receipt_digest + OR ((marker_document -> 'binding') ->> 'environmentId') IS DISTINCT FROM NEW.environment_id + OR ((marker_document -> 'binding') ->> 'clusterId') IS DISTINCT FROM NEW.cluster_id + OR ((marker_document -> 'binding') ->> 'namespace') IS DISTINCT FROM NEW.kubernetes_namespace + OR ((marker_document -> 'binding') ->> 'expectedClusterIncarnationUid') IS DISTINCT FROM NEW.expected_cluster_incarnation_uid::TEXT + OR ((marker_document -> 'binding') ->> 'expectedNamespaceUid') IS DISTINCT FROM NEW.expected_namespace_uid::TEXT + OR ((marker_document -> 'binding') ->> 'trustBindingDigest') IS DISTINCT FROM NEW.trust_binding_digest + OR ((marker_document -> 'binding') ->> 'trustConfigRevision') IS DISTINCT FROM NEW.trust_config_revision + OR ((marker_document -> 'binding') ->> 'apiBindingDigest') IS DISTINCT FROM NEW.api_binding_digest + OR ((marker_document -> 'binding') ->> 'apiConfigRevision') IS DISTINCT FROM NEW.api_config_revision + OR ((marker_document -> 'publicConfigMap') ->> 'name') IS DISTINCT FROM 'jwt-jwks' + OR (marker_document -> 'expectedDurableActive') IS DISTINCT FROM (NEW.expected_durable_active_json::jsonb) + OR (marker_document -> 'expectedPublishedActive') IS DISTINCT FROM (NEW.expected_published_active_json::jsonb) + OR ((marker_document -> 'pending') ->> 'generation') IS DISTINCT FROM NEW.target_generation::TEXT + OR ((marker_document -> 'pending') ->> 'kid') IS DISTINCT FROM NEW.target_kid + OR ((marker_document -> 'pending') ->> 'algorithm') IS DISTINCT FROM 'RS256' + OR ((marker_document -> 'pending') ->> 'publicKeyFingerprint') IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Account public generation marker is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_publication_receipt() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR intent_row.config_map_uid IS DISTINCT FROM NEW.config_map_uid + OR intent_row.expected_resource_version IS DISTINCT FROM NEW.expected_resource_version + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR NEW.expected_resource_version = NEW.observed_resource_version THEN + RAISE EXCEPTION 'Account JWT publication receipt does not match current intent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_mount_observation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; + receipt_row account_jwt_jwks_publication_receipts%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + SELECT receipt.* INTO receipt_row + FROM account_jwt_jwks_publication_receipts AS receipt + WHERE receipt.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.receipt_digest IS DISTINCT FROM NEW.publication_receipt_digest + OR intent_row.generation_marker_digest IS DISTINCT FROM NEW.generation_marker_digest + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR intent_row.public_key_fingerprint IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Mounted Account JWT correspondence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_reject_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT JWKS publication evidence is immutable' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER account_jwt_jwks_intent_current_guard + BEFORE INSERT ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_public_intent(); +CREATE TRIGGER account_jwt_jwks_receipt_current_guard + BEFORE INSERT ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_publication_receipt(); +CREATE TRIGGER account_jwt_jwks_mount_current_guard + BEFORE INSERT ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_mount_observation(); + +CREATE TRIGGER account_jwt_jwks_intent_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); + +CREATE TRIGGER account_jwt_jwks_intent_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_prepublication_intents + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_publication_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_mount_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql new file mode 100644 index 0000000000..2f22decf0f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql @@ -0,0 +1,466 @@ +-- Durable, operation-scoped probe plans for the interim Account-mounted JWT signer. +-- Plans bind existing desired-state, generation-result, JWKS publication, and mount evidence; +-- this migration creates no second key authority, validator endpoint, or promotion transition. +CREATE TABLE account_jwt_readiness_probe_plans ( + rotation_operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(64), + publication_intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + mounted_observation_digest VARCHAR(64) NOT NULL, + applicability_matrix_json TEXT NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + validator_inventory_complete BOOLEAN NOT NULL DEFAULT FALSE, + maximum_cache_age_seconds SMALLINT NOT NULL, + planned_at_epoch_seconds BIGINT NOT NULL, + not_before_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + plan_version SMALLINT NOT NULL DEFAULT 1, + plan_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_plan_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_operation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_result_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_intent_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_receipt_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_mount_observation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_jwks_mount_observations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_identity_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND desired_state_version > 1 + AND target_generation > COALESCE(expected_active_generation, 0) + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL + AND expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_published_generation IS NOT NULL AND expected_published_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_generation = expected_published_generation + AND expected_active_kid = expected_published_kid)) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_active_kid IS NULL OR expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$') + AND target_kid <> expected_active_kid + AND target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND publication_intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND plan_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_readiness_plan_trust_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_readiness_plan_inventory_check + CHECK (octet_length(applicability_matrix_json) BETWEEN 2 AND 8192), + CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version = 1), + CONSTRAINT account_jwt_readiness_plan_digest_unique + UNIQUE (rotation_operation_id, plan_digest) +); + +CREATE TABLE account_jwt_readiness_probe_entries ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL UNIQUE, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + registry_version SMALLINT NOT NULL DEFAULT 1, + entry_version BIGINT NOT NULL DEFAULT 1, + planned_issued_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + state VARCHAR(16) NOT NULL DEFAULT 'PLANNED', + terminal_outcome VARCHAR(16), + signing_attempted_at_epoch_seconds BIGINT, + compact_token_sha256 VARCHAR(64), + verification_receipt_version SMALLINT, + verification_source_entry_version BIGINT, + verified_at_epoch_seconds BIGINT, + verified_kid VARCHAR(64), + validator_instance_id VARCHAR(128), + validator_binding_digest VARCHAR(64), + validator_config_revision VARCHAR(128), + validator_peer_uri VARCHAR(256), + validator_peer_spki_sha256 VARCHAR(64), + verification_receipt_sha256 VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind), + CONSTRAINT account_jwt_readiness_probe_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_probe_jti_v4_check + CHECK (jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_readiness_probe_identity_check + CHECK (validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND target_generation > COALESCE(expected_active_generation, 0) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid), + CONSTRAINT account_jwt_readiness_probe_state_check + CHECK (state IN ('PLANNED', 'ISSUED', 'VERIFIED', 'RETIRED', 'CLEANED', 'EXPIRED', 'ABORTED') + AND (terminal_outcome IS NULL OR terminal_outcome IN ('EXPIRED', 'ABORTED')) + AND ((state IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NOT NULL) + OR (state NOT IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NULL))), + CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') + OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL OR verification_receipt_version = 1) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; +BEGIN + IF NEW.validator_inventory_complete THEN + RAISE EXCEPTION 'Readiness inventory is incomplete without authenticated validator evidence' + USING ERRCODE = '23514'; + END IF; + matrix := NEW.applicability_matrix_json::jsonb; + IF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness applicability must bind the exact partial Account profile set' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_inventory + BEFORE INSERT ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_inventory_guard(); + +CREATE FUNCTION account_jwt_readiness_plan_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness probe plans are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_immutable_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT readiness entries must begin PLANNED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.validator_id <> 'account-service' + OR NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' THEN + RAISE EXCEPTION 'Account JWT readiness canary shape is not fixed' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') + AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'applicableProfiles') + AS applicable(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND applicable.value ->> 'tokenProfile' = NEW.token_profile + AND applicable.value ->> 'audience' = NEW.audience + ) THEN + RAISE EXCEPTION 'Account JWT readiness profile is outside its applicability matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + + IF NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness probe identity is immutable' USING ERRCODE = '23514'; + END IF; + + IF NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Account JWT readiness entry version must advance once' USING ERRCODE = '23514'; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.signing_attempted_at_epoch_seconds + IS DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + OR NEW.verification_receipt_version IS DISTINCT FROM 1 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.verified_kid IS DISTINCT FROM OLD.target_kid + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_id IS DISTINCT FROM 'account-service' + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Verified readiness probe differs from its current immutable plan' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('ABORTED', 'EXPIRED') + AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 THEN + RETURN NEW; + END IF; + + -- This table records bounded non-authorizing observations only. RETIRED and every promotion + -- transition remain unavailable until their separate Account owner contracts are implemented. + RAISE EXCEPTION 'Account JWT readiness probe lifecycle transition is unavailable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql new file mode 100644 index 0000000000..edee4e5601 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql @@ -0,0 +1,570 @@ +-- Forward-only lifecycle extension for the existing Account-owned signer authority. The +-- generation operation remains immutable; one separate promotion operation binds it to the +-- authenticated Secret/JWKS/probe evidence and owns the PREPARED -> COMMITTED|ABORTED CAS. + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_action_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_slots_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_status_check; + +ALTER TABLE account_jwt_signer_promotion_operations + ADD COLUMN generation_operation_id UUID, + ADD COLUMN expected_cluster_incarnation_uid UUID, + ADD COLUMN expected_namespace_uid UUID, + ADD COLUMN materializer_trust_binding_digest VARCHAR(64), + ADD COLUMN materializer_trust_config_revision VARCHAR(128), + ADD COLUMN api_binding_digest VARCHAR(64), + ADD COLUMN api_config_revision VARCHAR(128), + ADD COLUMN expected_private_secret_uid UUID, + ADD COLUMN expected_public_config_map_uid UUID, + ADD COLUMN prepublication_intent_digest VARCHAR(64), + ADD COLUMN prepublication_receipt_digest VARCHAR(64), + ADD COLUMN mounted_observation_digest VARCHAR(64), + ADD COLUMN readiness_plan_digest VARCHAR(64), + ADD COLUMN readiness_evidence_digest VARCHAR(64), + ADD COLUMN expected_public_jwks_json TEXT, + ADD COLUMN expected_active_generation_marker_json TEXT, + ADD COLUMN private_promotion_observed_resource_version VARCHAR(256), + ADD COLUMN private_promotion_receipt_digest VARCHAR(64), + ADD COLUMN private_promotion_dispatched_at TIMESTAMPTZ, + ADD COLUMN active_jwks_observed_resource_version VARCHAR(256), + ADD COLUMN active_jwks_public_data_digest VARCHAR(64), + ADD COLUMN active_jwks_receipt_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_promotion_generation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_action_check + CHECK ((operation_action = 'MATERIALIZE_PENDING' + AND allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) + OR (operation_action = 'PROMOTE_PENDING' + AND allowed_private_slots_canonical_bytes = + '\x5b2263757272656e74222c2270656e64696e67222c2270726576696f7573225d'::bytea)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_status_check + CHECK (status IN ('PREPARED', 'COMMITTED', 'ABORTED')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_identity_check + CHECK (operation_action <> 'PROMOTE_PENDING' + OR (generation_operation_id IS NOT NULL + AND expected_cluster_incarnation_uid IS NOT NULL + AND expected_namespace_uid IS NOT NULL + AND materializer_trust_binding_digest IS NOT NULL + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision IS NOT NULL + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest IS NOT NULL + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND api_config_revision IS NOT NULL + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND expected_private_secret_uid IS NOT NULL + AND expected_public_config_map_uid IS NOT NULL + AND prepublication_intent_digest IS NOT NULL + AND prepublication_intent_digest ~ '^[0-9a-f]{64}$' + AND prepublication_receipt_digest IS NOT NULL + AND prepublication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest IS NOT NULL + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND readiness_plan_digest IS NOT NULL + AND readiness_plan_digest ~ '^[0-9a-f]{64}$' + AND readiness_evidence_digest IS NOT NULL + AND readiness_evidence_digest ~ '^[0-9a-f]{64}$' + AND expected_public_jwks_json IS NOT NULL + AND expected_active_generation_marker_json IS NOT NULL)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_uid_check + CHECK ((expected_cluster_incarnation_uid IS NULL + OR expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_namespace_uid IS NULL + OR expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_private_secret_uid IS NULL + OR expected_private_secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_public_config_map_uid IS NULL + OR expected_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_digest_check + CHECK ((materializer_trust_binding_digest IS NULL + OR materializer_trust_binding_digest ~ '^[0-9a-f]{64}$') + AND (api_binding_digest IS NULL OR api_binding_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_intent_digest IS NULL + OR prepublication_intent_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_receipt_digest IS NULL + OR prepublication_receipt_digest ~ '^[0-9a-f]{64}$') + AND (mounted_observation_digest IS NULL + OR mounted_observation_digest ~ '^[0-9a-f]{64}$') + AND (readiness_plan_digest IS NULL + OR readiness_plan_digest ~ '^[0-9a-f]{64}$') + AND (readiness_evidence_digest IS NULL + OR readiness_evidence_digest ~ '^[0-9a-f]{64}$') + AND (private_promotion_receipt_digest IS NULL + OR private_promotion_receipt_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_public_data_digest IS NULL + OR active_jwks_public_data_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_receipt_digest IS NULL + OR active_jwks_receipt_digest ~ '^[0-9a-f]{64}$')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_rv_check + CHECK ((private_promotion_observed_resource_version IS NULL + OR (private_promotion_observed_resource_version ~ '^[!-~]+$' + AND char_length(private_promotion_observed_resource_version) BETWEEN 1 AND 256)) + AND (active_jwks_observed_resource_version IS NULL + OR (active_jwks_observed_resource_version ~ '^[!-~]+$' + AND char_length(active_jwks_observed_resource_version) BETWEEN 1 AND 256))), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_content_check + CHECK ((expected_public_jwks_json IS NULL OR octet_length(expected_public_jwks_json) BETWEEN 1 AND 262144) + AND (expected_active_generation_marker_json IS NULL + OR octet_length(expected_active_generation_marker_json) BETWEEN 1 AND 16384)), + ADD CONSTRAINT account_jwt_signer_promotion_dispatch_check + CHECK ((private_promotion_receipt_digest IS NULL + OR private_promotion_dispatched_at IS NOT NULL) + AND (status <> 'COMMITTED' + OR (private_promotion_dispatched_at IS NOT NULL + AND private_promotion_receipt_digest IS NOT NULL + AND active_jwks_receipt_digest IS NOT NULL)) + AND (status <> 'ABORTED' + OR (private_promotion_dispatched_at IS NULL + AND private_promotion_receipt_digest IS NULL + AND active_jwks_receipt_digest IS NULL))); + +-- Enrollment is admitted only after both independently protected bindings and a live read of the +-- fixed pre-created public ConfigMap agree on the environment/cluster/namespace incarnation. +-- Existing rows with NULL pins are intentionally not backfilled or promoted. +ALTER TABLE account_jwt_signer_desired_states + ADD COLUMN enrollment_cluster_incarnation_uid UUID, + ADD COLUMN enrollment_namespace_uid UUID, + ADD COLUMN enrollment_materializer_binding_digest VARCHAR(64), + ADD COLUMN enrollment_materializer_config_revision VARCHAR(128), + ADD COLUMN enrollment_api_binding_digest VARCHAR(64), + ADD COLUMN enrollment_api_config_revision VARCHAR(128), + ADD COLUMN enrollment_public_config_map_uid UUID, + ADD COLUMN enrollment_public_config_map_resource_version VARCHAR(256), + ADD COLUMN enrollment_public_config_map_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_enrollment_shape_check + CHECK ((enrollment_cluster_incarnation_uid IS NULL + AND enrollment_namespace_uid IS NULL + AND enrollment_materializer_binding_digest IS NULL + AND enrollment_materializer_config_revision IS NULL + AND enrollment_api_binding_digest IS NULL + AND enrollment_api_config_revision IS NULL + AND enrollment_public_config_map_uid IS NULL + AND enrollment_public_config_map_resource_version IS NULL + AND enrollment_public_config_map_snapshot_digest IS NULL) + OR (enrollment_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_cluster_incarnation_uid IS NOT NULL + AND enrollment_namespace_uid IS NOT NULL + AND enrollment_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_materializer_binding_digest IS NOT NULL + AND enrollment_materializer_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_materializer_config_revision IS NOT NULL + AND enrollment_materializer_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_api_binding_digest IS NOT NULL + AND enrollment_api_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_api_config_revision IS NOT NULL + AND enrollment_api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_public_config_map_uid IS NOT NULL + AND enrollment_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_public_config_map_resource_version IS NOT NULL + AND enrollment_public_config_map_resource_version ~ '^[!-~]+$' + AND char_length(enrollment_public_config_map_resource_version) BETWEEN 1 AND 256 + AND enrollment_public_config_map_snapshot_digest IS NOT NULL + AND enrollment_public_config_map_snapshot_digest ~ '^[0-9a-f]{64}$')); + +-- PREPARED proof is immutable. Account first durably records its one-way peer dispatch before +-- returning mutation authority. Only the two exact public-only CAS receipts may then be filled +-- once, followed by one terminal state transition. No receipt includes, hashes, or returns +-- private Secret bytes. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + private_receipt_changed BOOLEAN; + private_dispatch_changed BOOLEAN; + jwks_receipt_changed BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF (NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.request_digest_version, NEW.request_digest, + NEW.expected_record_version, NEW.expected_previous_generation, NEW.expected_previous_kid, + NEW.target_generation, NEW.target_kid, NEW.target_algorithm, + NEW.target_public_key_fingerprint, NEW.expected_private_secret_resource_version, + NEW.expected_public_jwks_resource_version, NEW.expected_public_active_generation, + NEW.expected_public_active_kid, NEW.operation_action, + NEW.allowed_private_slots_canonical_bytes, NEW.generation_operation_id, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.materializer_trust_binding_digest, NEW.materializer_trust_config_revision, + NEW.api_binding_digest, NEW.api_config_revision, NEW.expected_private_secret_uid, + NEW.expected_public_config_map_uid, NEW.prepublication_intent_digest, + NEW.prepublication_receipt_digest, NEW.mounted_observation_digest, + NEW.readiness_plan_digest, NEW.readiness_evidence_digest, + NEW.expected_public_jwks_json, NEW.expected_active_generation_marker_json, + NEW.created_at) + IS DISTINCT FROM + (OLD.operation_id, OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, + OLD.custody_mode, OLD.request_digest_version, OLD.request_digest, + OLD.expected_record_version, OLD.expected_previous_generation, OLD.expected_previous_kid, + OLD.target_generation, OLD.target_kid, OLD.target_algorithm, + OLD.target_public_key_fingerprint, OLD.expected_private_secret_resource_version, + OLD.expected_public_jwks_resource_version, OLD.expected_public_active_generation, + OLD.expected_public_active_kid, OLD.operation_action, + OLD.allowed_private_slots_canonical_bytes, OLD.generation_operation_id, + OLD.expected_cluster_incarnation_uid, OLD.expected_namespace_uid, + OLD.materializer_trust_binding_digest, OLD.materializer_trust_config_revision, + OLD.api_binding_digest, OLD.api_config_revision, OLD.expected_private_secret_uid, + OLD.expected_public_config_map_uid, OLD.prepublication_intent_digest, + OLD.prepublication_receipt_digest, OLD.mounted_observation_digest, + OLD.readiness_plan_digest, OLD.readiness_evidence_digest, + OLD.expected_public_jwks_json, OLD.expected_active_generation_marker_json, + OLD.created_at) THEN + RAISE EXCEPTION 'Account JWT signer promotion request is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF OLD.status <> 'PREPARED' OR NEW.status NOT IN ('PREPARED', 'COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'Account JWT signer promotion is already terminal' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + + private_receipt_changed := + (NEW.private_promotion_observed_resource_version, + NEW.private_promotion_receipt_digest) + IS DISTINCT FROM + (OLD.private_promotion_observed_resource_version, + OLD.private_promotion_receipt_digest); + private_dispatch_changed := + NEW.private_promotion_dispatched_at IS DISTINCT FROM OLD.private_promotion_dispatched_at; + jwks_receipt_changed := + (NEW.active_jwks_observed_resource_version, NEW.active_jwks_public_data_digest, + NEW.active_jwks_receipt_digest) + IS DISTINCT FROM + (OLD.active_jwks_observed_resource_version, OLD.active_jwks_public_data_digest, + OLD.active_jwks_receipt_digest); + + IF private_receipt_changed THEN + IF OLD.private_promotion_receipt_digest IS NOT NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.private_promotion_observed_resource_version IS NULL + OR jwks_receipt_changed OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT private promotion receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF private_dispatch_changed THEN + IF OLD.private_promotion_dispatched_at IS NOT NULL + OR NEW.private_promotion_dispatched_at IS NULL + OR NEW.status <> 'PREPARED' + OR private_receipt_changed OR jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT private promotion dispatch is not a first durable authorization' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF jwks_receipt_changed THEN + IF OLD.active_jwks_receipt_digest IS NOT NULL + OR NEW.active_jwks_receipt_digest IS NULL + OR NEW.active_jwks_observed_resource_version IS NULL + OR NEW.active_jwks_public_data_digest IS NULL + OR OLD.private_promotion_receipt_digest IS NULL + OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT active JWKS receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF NEW.status = OLD.status AND NOT private_dispatch_changed + AND NOT private_receipt_changed AND NOT jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT promotion update has no exact receipt transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'COMMITTED' + AND (NEW.private_promotion_dispatched_at IS NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.active_jwks_receipt_digest IS NULL) THEN + RAISE EXCEPTION 'JWT promotion cannot commit without both exact resource receipts' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'ABORTED' + AND (OLD.private_promotion_dispatched_at IS NOT NULL + OR OLD.private_promotion_receipt_digest IS NOT NULL + OR OLD.active_jwks_receipt_digest IS NOT NULL) THEN + RAISE EXCEPTION 'Dispatched JWT promotion must remain PREPARED for reconciliation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + IF (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.private_secret_name, NEW.public_jwks_config_map_name, NEW.created_at, + NEW.enrollment_cluster_incarnation_uid, NEW.enrollment_namespace_uid, + NEW.enrollment_materializer_binding_digest, NEW.enrollment_materializer_config_revision, + NEW.enrollment_api_binding_digest, NEW.enrollment_api_config_revision, + NEW.enrollment_public_config_map_uid, NEW.enrollment_public_config_map_resource_version, + NEW.enrollment_public_config_map_snapshot_digest) + IS DISTINCT FROM + (OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, OLD.custody_mode, + OLD.private_secret_name, OLD.public_jwks_config_map_name, OLD.created_at, + OLD.enrollment_cluster_incarnation_uid, OLD.enrollment_namespace_uid, + OLD.enrollment_materializer_binding_digest, OLD.enrollment_materializer_config_revision, + OLD.enrollment_api_binding_digest, OLD.enrollment_api_config_revision, + OLD.enrollment_public_config_map_uid, OLD.enrollment_public_config_map_resource_version, + OLD.enrollment_public_config_map_snapshot_digest) + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + -- Creating a generation operation is the only transition from an idle state to a new key + -- request. Active identities and publication fences remain unchanged. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NOT NULL AND NEW.prepared_operation_id IS NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + IF OLD.enrollment_cluster_incarnation_uid IS NULL + OR OLD.enrollment_namespace_uid IS NULL + OR OLD.enrollment_materializer_binding_digest IS NULL + OR OLD.enrollment_api_binding_digest IS NULL + OR OLD.enrollment_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'JWT signer state has no independently protected enrollment pins' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + PERFORM 1 FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.generation_operation_id + AND generation_op.environment_id = NEW.environment_id + AND generation_op.cluster_id = NEW.cluster_id + AND generation_op.kubernetes_namespace = NEW.kubernetes_namespace + AND generation_op.custody_mode = NEW.custody_mode + AND generation_op.expected_record_version = OLD.record_version + AND generation_op.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND generation_op.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND generation_op.expected_published_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND generation_op.expected_published_kid IS NOT DISTINCT FROM OLD.published_active_kid; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation pointer is not the exact current Account operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Enter PREPARED only after insertion of the exact durable promotion request. + IF OLD.generation_operation_id IS NOT NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NOT NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = NEW.prepared_operation_id + AND promotion.generation_operation_id = OLD.generation_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version = OLD.record_version + AND promotion.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND promotion.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND promotion.expected_public_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND promotion.expected_public_active_kid IS NOT DISTINCT FROM OLD.published_active_kid + AND promotion.status = 'PREPARED' + AND promotion.operation_action = 'PROMOTE_PENDING'; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT PREPARED pointer is not the exact Account promotion operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Close only the exact PREPARED operation. COMMITTED changes both active fences to target; + -- ABORTED preserves both previous fences. No resource observation can perform either CAS. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NOT NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NULL THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = OLD.prepared_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version + 1 = OLD.record_version + AND promotion.status IN ('COMMITTED', 'ABORTED'); + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT promotion terminal transition has no exact durable result' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + IF operation_row.status = 'COMMITTED' THEN + IF NEW.durable_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.durable_active_kid IS DISTINCT FROM operation_row.target_kid + OR NEW.published_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.published_active_kid IS DISTINCT FROM operation_row.target_kid THEN + RAISE EXCEPTION 'Committed JWT signer and published active fences must equal target' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + ELSIF NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid THEN + RAISE EXCEPTION 'Aborted JWT signer operation must preserve previous active fences' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Account JWT signer state transition is not in the lifecycle CAS' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; +END; +$$; + +CREATE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.receipt_digest IS DISTINCT FROM NEW.generation_receipt_digest + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT validator_inventory_complete, expires_at_epoch_seconds + INTO plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_promotion_insert_guard + BEFORE INSERT ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_promotion_insert_guard(); + +CREATE FUNCTION account_jwt_signer_promotion_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_jwt_signer_promotion_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_promotion_no_truncate(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql new file mode 100644 index 0000000000..c2d6b68277 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql @@ -0,0 +1,125 @@ +-- One durable winner may emit the exact current operation's readiness probes to its authenticated +-- harness. A claim is a one-shot concurrency fence, not delivery proof, validator evidence, or +-- signer authority; it is never cleared after an ambiguous response. +CREATE TABLE account_jwt_readiness_delivery_claims ( + rotation_operation_id UUID PRIMARY KEY, + plan_digest VARCHAR(64) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + materializer_trust_binding_digest VARCHAR(64) NOT NULL, + materializer_trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + readiness_binding_digest VARCHAR(64) NOT NULL, + readiness_config_revision VARCHAR(128) NOT NULL, + readiness_binding_valid_until_epoch_seconds BIGINT NOT NULL, + validator_id VARCHAR(63) NOT NULL, + validator_instance_id VARCHAR(128) NOT NULL, + validator_peer_uri VARCHAR(256) NOT NULL, + validator_peer_spki_sha256 VARCHAR(64) NOT NULL, + claimed_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + claim_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_delivery_claim_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_delivery_claim_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND readiness_binding_digest ~ '^[0-9a-f]{64}$' + AND readiness_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND readiness_binding_valid_until_epoch_seconds > claimed_at_epoch_seconds + AND validator_id = 'account-service' + AND validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$' + AND validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND claimed_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > claimed_at_epoch_seconds + AND claim_digest ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_insert_guard + BEFORE INSERT ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_guard(); + +CREATE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness delivery claims are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql new file mode 100644 index 0000000000..4861806bc2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql @@ -0,0 +1,67 @@ +-- Durable immutable owner observations are bound to a readiness plan, but remain partial +-- non-authorizing evidence. A stored Deployment/ReplicaSet/Pod inventory is not probe acceptance. +CREATE TABLE account_jwt_validator_inventory_snapshots ( + snapshot_digest VARCHAR(64) PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + observed_at VARCHAR(40) NOT NULL, + canonical_snapshot BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_validator_inventory_snapshot_identity_check + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND length(observed_at) BETWEEN 20 AND 40 + AND observed_at ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T.*Z$' + AND octet_length(canonical_snapshot) BETWEEN 2 AND 4194304), + CONSTRAINT account_jwt_validator_inventory_snapshot_plan_identity_unique + UNIQUE (snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT validator inventory snapshots are immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_immutable + BEFORE UPDATE OR DELETE ON account_jwt_validator_inventory_snapshots + FOR EACH ROW EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_no_truncate + BEFORE TRUNCATE ON account_jwt_validator_inventory_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); +-- [jooq ignore stop] + +ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT; diff --git a/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql new file mode 100644 index 0000000000..3371d9d86a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql @@ -0,0 +1,119 @@ +CREATE SEQUENCE account_control_ui_source_fence START WITH 1; + +CREATE TABLE account_control_ui_issuance_operations ( + request_id UUID PRIMARY KEY, + operation_id UUID NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_mac_key_id VARCHAR(32) NOT NULL, + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), + signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), + issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), + expires_at_epoch_second BIGINT NOT NULL, + recovery_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), + token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + pending_registry BYTEA, + active_registry BYTEA, + pending_receipt BYTEA, + committed_at TIMESTAMPTZ, + recovery_failed_at TIMESTAMPTZ, + revocation_receipt BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second <= issued_at_epoch_second + 300), + CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL + AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) + OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL + AND ((pending_receipt IS NULL AND committed_at IS NULL) + OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), + CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), + CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) +); + +CREATE TABLE account_control_ui_response_envelopes ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), + recovery_expires_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( + recovery_expires_at > to_timestamp(issued_at_epoch_second) + AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) + AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); + +CREATE FUNCTION account_control_ui_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) + OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') + OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') + OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') + OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') + OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) + OR (OLD.status <> 'PREPARED' AND + (NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry + OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) + OR (NEW.status IN ('REVOKING','REVOKED') AND + (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) + OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN + RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_response_envelopes e + WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN + RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be truncated' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_control_ui_response_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui response evidence is immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_control_ui_issuance_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); +CREATE TRIGGER account_control_ui_issuance_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_response_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +CREATE TRIGGER account_control_ui_response_no_truncate + BEFORE TRUNCATE ON account_control_ui_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..970109378e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -0,0 +1,595 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +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 java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical PostgreSQL proof for the exact, read-only committed-issuance repository. + * + *

The SQL fixture advances only the actual V74 row through its guarded storage states. Its + * opaque payloads establish neither control-ui token authority nor genuine authorization issuance, + * protected-response encryption, or registry activation. + */ +@SuppressWarnings("resource") +class AccountControlUiCommittedIssuanceRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set schemas = new HashSet<>(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropTestOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : schemas) { + if (!schema.matches("account_control_ui_committed_[a-f0-9]{32}")) { + throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void readsOnlyExactCommittedEvidenceInsideTheOwnerTransaction() { + Context context = context(); + IssuanceSeed seed = context.insertCandidate(); + + assertThatThrownBy(() -> context.repository.readCommitted(seed.tokenHash())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed Account issuance read requires an Account transaction"); + + assertThatThrownBy(() -> context.commitCandidate(seed)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Protected original control-ui response is absent"); + assertThat(context.status(seed.requestId())).isEqualTo("CANDIDATE"); + + context.insertProtectedResponse(seed); + context.commitCandidate(seed); + var evidence = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + + assertThat(evidence.requestId()).isEqualTo(seed.requestId()); + assertThat(evidence.operationId()).isEqualTo(seed.operationId()); + assertThat(evidence.tokenJti()).isEqualTo(seed.tokenJti()); + assertThat(evidence.accountId()).isEqualTo(context.owner().accountId()); + assertThat(evidence.tenantId()).isEqualTo(context.owner().tenantId()); + assertThat(evidence.callerWorkload()).isEqualTo(seed.callerWorkload()); + assertThat(evidence.callerContextId()).isEqualTo(seed.callerContextId()); + assertThat(evidence.requestDigest()).isEqualTo(seed.requestDigest()); + assertThat(evidence.claims()).containsExactly(seed.claims()); + assertThat(evidence.source()).containsExactly(seed.source()); + assertThat(evidence.bundle()).containsExactly(seed.bundle()); + assertThat(evidence.signerReceipt()).containsExactly(seed.signerReceipt()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(seed.issuedAtEpochSecond()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(seed.expiresAtEpochSecond()); + assertThat(evidence.status()).isEqualTo("COMMITTED"); + assertThat(evidence.tokenHash()).isEqualTo(seed.tokenHash()); + assertThat(evidence.pendingRegistry()).containsExactly(seed.pendingRegistry()); + assertThat(evidence.activeRegistry()).containsExactly(seed.activeRegistry()); + assertThat(evidence.pendingReceipt()).containsExactly(seed.pendingReceipt()); + assertThat(evidence.committedAt()).isNotNull(); + assertThat(evidence.recoveryFailedAt()).isNull(); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT owner_binding FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.ownerBinding()); + + byte[] exposedClaims = evidence.claims(); + exposedClaims[0] ^= 0x7f; + assertThat( + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow().claims())) + .containsExactly(seed.claims()); + } + + @Test + void missingCandidateAndRevokedIssuancesDoNotReadAsCommitted() { + Context context = context(); + IssuanceSeed candidate = context.insertCandidate(); + IssuanceSeed revoked = context.insertCommitted(); + context.revokeCommitted(revoked); + + assertThat(context.inTransaction(() -> context.repository.readCommitted("f".repeat(64)))) + .isEmpty(); + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.readCommitted(candidate.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + assertThat(context.status(candidate.requestId())).isEqualTo("CANDIDATE"); + assertThat(context.status(revoked.requestId())).isEqualTo("REVOKED"); + assertThatThrownBy( + () -> + context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + @Test + void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET source_payload = ? WHERE request_id = ?", + bytes("test-only-rewritten-source"), + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_response_envelopes " + + "SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-rewritten-envelope"), + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + + var retained = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + assertThat(retained.source()).containsExactly(seed.source()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + } + + @Test + void committedReadShareLockLinearizesBeforeConcurrentRevocation() throws Exception { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + CountDownLatch readerHasLoadedEvidence = new CountDownLatch(1); + CountDownLatch releaseReaderTransaction = new CountDownLatch(1); + CountDownLatch revocationIsAboutToUpdate = new CountDownLatch(1); + AtomicInteger readerPid = new AtomicInteger(); + AtomicInteger revokerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + + Future reader = + executor.submit( + () -> + context.inTransaction( + () -> { + var evidence = + context.repository.readCommitted(seed.tokenHash()).orElseThrow(); + readerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + readerHasLoadedEvidence.countDown(); + await(releaseReaderTransaction, "reader transaction release"); + return evidence; + })); + Future revocation; + try { + assertThat(readerHasLoadedEvidence.await(5, TimeUnit.SECONDS)).isTrue(); + revocation = + executor.submit( + () -> + context.inTransaction( + () -> { + revokerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + revocationIsAboutToUpdate.countDown(); + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId()); + return null; + })); + assertThat(revocationIsAboutToUpdate.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + waitUntilBlockedBy( + context, revokerPid.get(), readerPid.get(), TimeUnit.SECONDS.toNanos(5))) + .as("the revocation UPDATE waits on the repository's FOR SHARE row lock") + .isTrue(); + assertThat(revocation.isDone()).isFalse(); + } finally { + releaseReaderTransaction.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)) + .as("reader and revocation transactions terminate after releasing the row lock") + .isTrue(); + } + } + + assertThat(reader.get(5, TimeUnit.SECONDS).status()).isEqualTo("COMMITTED"); + revocation.get(5, TimeUnit.SECONDS); + assertThat(context.status(seed.requestId())).isEqualTo("REVOKING"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.readCommitted(seed.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + private static boolean waitUntilBlockedBy( + Context context, int waitingPid, int blockingPid, long timeoutNanos) + throws InterruptedException { + long deadline = System.nanoTime() + timeoutNanos; + while (System.nanoTime() < deadline) { + Boolean blocked = + context + .adminDsl + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE pid = ? AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waitingPid, + blockingPid) + .get(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static void await(CountDownLatch latch, String purpose) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + purpose); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + purpose, interrupted); + } + } + + private Context context() { + String schema = "account_control_ui_committed_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Context(transactionDsl, adminDsl, dataSource); + } + + private static FreshTenantCreationEvidence tenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String tenantKey = "committed-issuance-" + requestId.toString().substring(0, 12); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, tenantKey, "test tenant", null); + long sourceGameRowId = 7001L; + String provenance = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance, + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance)); + } + + private static String tokenHash() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static String digest() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record OwnerIdentity(UUID accountId, UUID tenantId) {} + + private record IssuanceSeed( + UUID requestId, + UUID operationId, + UUID tokenJti, + String callerWorkload, + UUID callerContextId, + String requestDigest, + byte[] claims, + byte[] source, + byte[] bundle, + byte[] signerReceipt, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + OffsetDateTime recoveryExpiresAt, + String tokenHash, + byte[] pendingRegistry, + byte[] activeRegistry, + byte[] pendingReceipt, + byte[] encryptedResponse, + byte[] ownerBinding) {} + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountControlUiCommittedIssuanceRepository repository; + private final OwnerIdentity owner; + + Context(DSLContext transactionDsl, DSLContext adminDsl, DriverManagerDataSource dataSource) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + repository = new AccountControlUiCommittedIssuanceRepository(transactionDsl); + owner = + inTransaction( + () -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("control-ui-committed-" + suffix); + account.setEmail("control-ui-committed-" + suffix + "@example.test"); + account.setPasswordHash("test-only-account-password-hash"); + Account saved = new AccountRepository(transactionDsl).save(account); + UUID tenantId = UUID.randomUUID(); + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") + .importVerified(tenantEvidence(tenantId)); + return new OwnerIdentity(saved.getAccountUuid(), tenantId); + }); + } + + OwnerIdentity owner() { + return owner; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + IssuanceSeed insertCandidate() { + IssuanceSeed seed = newSeed(); + inTransactionWithoutResult(() -> insertPrepared(seed)); + inTransactionWithoutResult(() -> advanceToCandidate(seed)); + return seed; + } + + IssuanceSeed insertCommitted() { + IssuanceSeed seed = insertCandidate(); + insertProtectedResponse(seed); + commitCandidate(seed); + return seed; + } + + void insertProtectedResponse(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?)", + seed.operationId(), + seed.encryptedResponse(), + seed.ownerBinding(), + seed.recoveryExpiresAt())); + } + + void commitCandidate(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'CANDIDATE'", + seed.pendingReceipt(), + seed.requestId())); + } + + void revokeCommitted(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId())); + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKED', revocation_receipt = ? " + + "WHERE request_id = ? AND status = 'REVOKING'", + bytes("test-only-revocation-receipt"), + seed.requestId())); + } + + String status(UUID requestId) { + return inTransaction( + () -> + transactionDsl + .fetchOne( + "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", + requestId) + .get(0, String.class)); + } + + private void insertPrepared(IssuanceSeed seed) { + transactionDsl.execute( + "INSERT INTO account_control_ui_issuance_operations (" + + "request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED')", + seed.requestId(), + seed.operationId(), + seed.tokenJti(), + owner.accountId(), + owner.tenantId(), + seed.callerWorkload(), + seed.callerContextId(), + "test-mac1", + seed.requestDigest(), + seed.claims(), + seed.source(), + seed.bundle(), + seed.signerReceipt(), + seed.issuedAtEpochSecond(), + seed.expiresAtEpochSecond(), + seed.recoveryExpiresAt()); + } + + private void advanceToCandidate(IssuanceSeed seed) { + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE request_id = ? AND status = 'PREPARED'", + seed.tokenHash(), + seed.pendingRegistry(), + seed.activeRegistry(), + seed.requestId()); + } + + private static IssuanceSeed newSeed() { + UUID requestId = UUID.randomUUID(); + long issuedAt = Instant.now().getEpochSecond(); + return new IssuanceSeed( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://test-only/logging-admin", + UUID.randomUUID(), + digest(), + bytes("test-only-claims-" + requestId), + bytes("test-only-source-" + requestId), + bytes("test-only-authority-bundle-" + requestId), + bytes("test-only-signer-receipt-" + requestId), + issuedAt, + issuedAt + 300, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC), + tokenHash(), + bytes("test-only-pending-registry-" + requestId), + bytes("test-only-active-registry-" + requestId), + bytes("test-only-pending-receipt-" + requestId), + bytes("opaque-test-only-encrypted-response-fixture-" + requestId), + bytes("opaque-test-only-owner-binding-" + requestId)); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java new file mode 100644 index 0000000000..23b8988963 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java @@ -0,0 +1,772 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.KeyStore; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.BindingRejectedException; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical loopback HTTPS proof for Account's production pinned-CA JWKS API transport only. */ +class AccountJwtJwksApiTransportTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String TEST_BEARER = "test-only-loopback-bearer"; + private static final char[] KEYSTORE_PASSWORD = "firemud-test".toCharArray(); + private static final Duration NORMAL_TIMEOUT = Duration.ofSeconds(3); + private static final Duration STALL_TIMEOUT = Duration.ofMillis(350); + private static final byte[] SELF_REVIEW = + (""" + {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview", + "status":{"userInfo":{"username":"%s"}}} + """ + .formatted(API_USERNAME)) + .getBytes(StandardCharsets.UTF_8); + private static final byte[] KUBE_SYSTEM_NAMESPACE = + namespaceJson("kube-system", KUBE_SYSTEM_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] TARGET_NAMESPACE = + namespaceJson(NAMESPACE, NAMESPACE_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] CONFIG_MAP = + (""" + {"apiVersion":"v1","kind":"ConfigMap","metadata":{ + "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}} + """ + .formatted(NAMESPACE, CONFIG_MAP_UID)) + .getBytes(StandardCharsets.UTF_8); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final List servers = new ArrayList<>(); + + @BeforeAll + static void createEphemeralPki() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted")); + TestAuthority trustedAuthority = createAuthority(trustedDirectory, "account-jwks-test-ca"); + TestServerCertificate trustedServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-localhost", "localhost"); + + Path untrustedDirectory = Files.createDirectories(temporaryDirectory.resolve("untrusted")); + TestAuthority untrustedAuthority = + createAuthority(untrustedDirectory, "account-jwks-untrusted-ca"); + + TestServerCertificate wrongHostnameServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-wrong-host", "wrong.example"); + pki = + new TestPki( + Files.readAllBytes(trustedAuthority.certificate()), + Files.readAllBytes(untrustedAuthority.certificate()), + trustedServer, + wrongHostnameServer); + } + + @AfterEach + void stopLocalServers() { + servers.forEach(server -> server.stop(0)); + } + + @Test + void pinnedCaAndHostnameReachTheFixedKubernetesPathsOverRealHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + requests.add( + exchange.getRequestMethod() + " " + exchange.getRequestURI().getRawPath()); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respondForKubernetesRequest(exchange); + }); + AccountJwtJwksConfigMapClient client = + new AccountJwtJwksConfigMapClient( + transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT)); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("7"); + assertThat(requests) + .containsExactly( + "POST /apis/authentication.k8s.io/v1/selfsubjectreviews", + "GET /api/v1/namespaces/kube-system", + "GET /api/v1/namespaces/" + NAMESPACE, + "GET /api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks"); + assertThat(authorizationHeaders).hasValue(4); + } + + @Test + void protectedInventoryOperationsUseOnlyFixedNamespaceGetPathsOverPinnedHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + requests.add( + exchange.getRequestMethod() + + " " + + exchange.getRequestURI().getRawPath() + + (query == null ? "" : "?" + query)); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respond(exchange, 200, "{}".getBytes(StandardCharsets.UTF_8)); + }); + AccountJwtJwksApiBinding client = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + ApiResponse deployment = operation.readValidatorDeployment(inventory, validator); + ApiResponse pods = operation.listValidatorPods(inventory, validator, "page/+token="); + ApiResponse replicaSet = + operation.readValidatorReplicaSet(inventory, validator, "player-service-abcde"); + assertThat(deployment.statusCode()).isEqualTo(200); + assertThat(pods.statusCode()).isEqualTo(200); + assertThat(replicaSet.statusCode()).isEqualTo(200); + } + + assertThat(requests) + .containsExactly( + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/deployments/player-service", + "GET /api/v1/namespaces/" + + NAMESPACE + + "/pods?labelSelector=app%3Dplayer-service%2Cfiremud.io%2Fcomponent%3Djwt-validator" + + "&limit=250&continue=page%2F%2Btoken%3D", + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/replicasets/player-service-abcde"); + assertThat(authorizationHeaders).hasValue(3); + } + + @Test + void replicaSetReadRejectsCallerSuppliedPathCharacters() throws Exception { + AccountJwtJwksApiBinding client = + transportBinding( + startServer(pki.trustedServer(), exchange -> respond(exchange, 200, new byte[0])), + pki.trustedCa(), + NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + assertThatThrownBy( + () -> operation.readValidatorReplicaSet(inventory, validator, "../secrets")) + .isInstanceOf(BindingRejectedException.class) + .hasNoCause(); + } + } + + @Test + void serverCertificateFromAnUnpinnedCaIsRejectedByTheProductionTransport() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.untrustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void wrongHostnameIsRejectedEvenWhenTheServingCertificateChainsToThePinnedCa() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.wrongHostnameServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void redirectIsReturnedButNeverFollowed() throws Exception { + AtomicInteger redirectTargetCalls = new AtomicInteger(); + HttpsServer redirectTarget = + startServer( + pki.trustedServer(), + exchange -> { + redirectTargetCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + List sourceRequests = new CopyOnWriteArrayList<>(); + HttpsServer source = + startServer( + pki.trustedServer(), + exchange -> { + sourceRequests.add(exchange.getRequestURI().getRawPath()); + Headers headers = exchange.getResponseHeaders(); + headers.set( + "Location", + "https://localhost:" + redirectTarget.getAddress().getPort() + "/target"); + respond(exchange, 302, new byte[0]); + }); + AccountJwtJwksApiBinding binding = transportBinding(source, pki.trustedCa(), NORMAL_TIMEOUT); + + ApiResponse response = send(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(response.statusCode()).isEqualTo(302); + assertThat(sourceRequests).containsExactly("/api/v1/namespaces/kube-system"); + assertThat(redirectTargetCalls).hasValue(0); + } + + @Test + void stalledPostHeaderBodyIsBoundedByTheWholeResponseDeadline() throws Exception { + CountDownLatch bodyStarted = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + try (OutputStream body = exchange.getResponseBody()) { + body.write('{'); + body.flush(); + bodyStarted.countDown(); + releaseBody.await(3, TimeUnit.SECONDS); + } catch (IOException ignored) { + // The client closes the response stream when its absolute deadline expires. + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), STALL_TIMEOUT); + long startedAt = System.nanoTime(); + + try { + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + assertThat(bodyStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(Duration.ofNanos(System.nanoTime() - startedAt)).isLessThan(Duration.ofSeconds(2)); + } finally { + releaseBody.countDown(); + } + } + + @Test + void oversizedHttpsResponseIsRejectedWithoutAcceptingPartialBytes() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + byte[] oversized = new byte[1024 * 1024 + 1]; + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, oversized); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_JWKS_CONFIG_MAP); + + assertThat(handlerCalls).hasValue(1); + } + + @Test + void rootOwnedReadOnlyProjectionAllowsRootWritableParentsAndSafeBearerRenewal() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("renewal"); + AccountJwtJwksApiBinding binding = fixture.binding(); + + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + ApiOperation inFlight = binding.beginOperation(); + fixture.projectToken("..0002", "renewed-test-bearer", "token"); + + assertThatThrownBy(() -> inFlight.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + inFlight.close(); + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + } + + @Test + void credentialModeAndFrozenTrustFileIdentityDriftAreRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("drift"); + AccountJwtJwksApiBinding binding = fixture.binding(); + binding.current(); + + Files.setPosixFilePermissions(fixture.currentToken(), Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(binding::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles ownerFixture = protectedFiles("owner-drift"); + ownerFixture.binding().current(); + Files.setAttribute(ownerFixture.currentToken(), "unix:uid", 65534L, LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(ownerFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles groupFixture = protectedFiles("group-drift"); + groupFixture.binding().current(); + Object gid = + Files.getAttribute(groupFixture.currentToken(), "unix:gid", LinkOption.NOFOLLOW_LINKS); + Files.setAttribute( + groupFixture.currentToken(), + "unix:gid", + ((Number) gid).longValue() == 0L ? 1L : 0L, + LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(groupFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles trustFixture = protectedFiles("trust-drift"); + trustFixture.binding().current(); + Path replacementCa = trustFixture.caPath().resolveSibling("replacement-serving-ca.pem"); + Files.writeString(replacementCa, "test-only-public-serving-ca", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + replacementCa, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.move(replacementCa, trustFixture.caPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(trustFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles bindingFixture = protectedFiles("binding-drift"); + bindingFixture.binding().current(); + Path replacementBinding = + bindingFixture.bindingPath().resolveSibling("replacement-binding.json"); + Files.write(replacementBinding, Files.readAllBytes(bindingFixture.bindingPath())); + Files.setPosixFilePermissions(replacementBinding, PosixFilePermissions.fromString("r--r-----")); + Files.move( + replacementBinding, bindingFixture.bindingPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(bindingFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + @Test + void groupOrOtherWritableProtectedProjectionDirectoryIsRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("writable-directory"); + Files.setPosixFilePermissions( + fixture.trustRoot(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + + assertThatThrownBy(fixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + private static void assertTransportFailure(AccountJwtJwksApiBinding binding, ApiCall call) { + assertThatThrownBy(() -> send(binding, call)) + .isInstanceOf(AccountJwtJwksApiBinding.ApiTransportException.class) + .hasMessage("Account JWT JWKS Kubernetes API request failed"); + } + + private static ApiResponse send(AccountJwtJwksApiBinding binding, ApiCall call) { + try (ApiOperation operation = binding.beginOperation()) { + return operation.send(call, null); + } + } + + private static void assumeRootCanCreateRootOwnedFixtures() throws Exception { + Object uid = Files.getAttribute(temporaryDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Assumptions.assumeTrue(uid instanceof Number number && number.longValue() == 0L); + } + + private ProtectedFiles protectedFiles(String label) throws Exception { + Path root = Files.createDirectories(temporaryDirectory.resolve(label)); + Path trustRoot = Files.createDirectory(root.resolve("account-jwt-api")); + Path tokenRoot = Files.createDirectory(root.resolve("account-jwt-api-token")); + Path bindingPath = trustRoot.resolve("binding.json"); + Path caPath = trustRoot.resolve("serving-ca.pem"); + Path tokenPath = tokenRoot.resolve("token"); + byte[] caBytes = "test-only-public-serving-ca".getBytes(StandardCharsets.UTF_8); + Files.write(caPath, caBytes); + Path firstVersion = Files.createDirectory(tokenRoot.resolve("..0001")); + Path firstToken = firstVersion.resolve("token"); + Files.writeString(firstToken, "initial-test-bearer"); + Files.createSymbolicLink(tokenRoot.resolve("..data"), Path.of("..0001")); + Files.createSymbolicLink(tokenPath, Path.of("..data/token")); + applyPermissions(trustRoot, "rwxr-xr-x"); + applyPermissions(tokenRoot, "rwxr-xr-x"); + applyPermissions(firstVersion, "rwxr-xr-x"); + Files.createFile(bindingPath); + applyPermissions(bindingPath, "r--r-----"); + applyPermissions(caPath, "r--r-----"); + applyPermissions(firstToken, "r--r-----"); + writeBinding(bindingPath, caPath, tokenPath, caBytes); + return new ProtectedFiles( + bindingPath, + trustRoot, + caPath, + tokenRoot, + tokenPath, + firstToken, + AccountJwtJwksApiBinding.forProtectedFilesTest( + bindingPath, trustRoot, caPath, tokenRoot, tokenPath)); + } + + private static void writeBinding(Path bindingPath, Path caPath, Path tokenPath, byte[] caBytes) + throws Exception { + Map values = new LinkedHashMap<>(); + values.put("version", "account-jwt-jwks-api-binding/v1"); + values.put("enabled", "true"); + values.put("configRevision", "physical-file-test-1"); + values.put("environmentId", "prod"); + values.put("clusterId", "loopback-cluster"); + values.put("apiServerUrl", "https://localhost:6443"); + values.put("tlsServerName", "localhost"); + values.put("servingCaPath", caPath.toString()); + values.put("servingCaSha256", sha256(caBytes)); + values.put("bearerTokenPath", tokenPath.toString()); + values.put("namespace", NAMESPACE); + values.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + values.put("expectedNamespaceUid", NAMESPACE_UID); + values.put("expectedApiUsername", API_USERNAME); + values.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + String placeholder = mapper.writeValueAsString(values); + tools.jackson.databind.JsonNode binding = mapper.readTree(placeholder); + values.put("bindingDigest", AccountJwtJwksApiBinding.computeBindingDigest(binding)); + Files.writeString(bindingPath, mapper.writeValueAsString(values), StandardCharsets.UTF_8); + } + + private static void applyPermissions(Path path, String mode) throws IOException { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); + } + + private AccountJwtJwksApiBinding transportBinding( + HttpsServer server, byte[] trustedCa, Duration timeout) throws Exception { + ParsedBinding binding = + new ParsedBinding( + "transport-test-1", + "prod", + "loopback-cluster", + java.net.URI.create("https://localhost:" + server.getAddress().getPort() + "/"), + "localhost", + Path.of("/not-read-by-transport-test/trusted-ca.pem"), + sha256(trustedCa), + Path.of("/not-read-by-transport-test/bearer-token"), + NAMESPACE, + KUBE_SYSTEM_UID, + NAMESPACE_UID, + API_USERNAME, + "f".repeat(64)); + return AccountJwtJwksApiBinding.forTransportTest(binding, trustedCa, TEST_BEARER, timeout); + } + + private static ProtectedInventory validatorInventoryForTransport() throws Exception { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", "44444444-4444-4444-8444-444444444444"); + validator.put( + "selector", Map.of("app", "player-service", "firemud.io/component", "jwt-validator")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", "registry.example/firemud/player@sha256:" + "a".repeat(64)); + validator.put("jwksUri", "https://account-api.test/.well-known/jwks.json"); + validator.put("maxCacheAgeSeconds", 60); + validator.put( + "profiles", + List.of( + Map.of( + "tokenProfile", "game-session-account-delegation", + "audience", "account-service"))); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-prod/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of( + "podUid", "55555555-5555-4555-8555-555555555555", + "podIp", "10.0.0.10", + "leafSpkiSha256", "b".repeat(64)))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", "inventory-r1"); + root.put("environmentId", "prod"); + root.put("clusterId", "loopback-cluster"); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "transport-test-1"); + root.put("apiBindingDigest", "f".repeat(64)); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + var unsigned = mapper.readTree(mapper.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(mapper.writeValueAsBytes(root)); + } + + private HttpsServer startServer(TestServerCertificate certificate, HttpHandler handler) + throws Exception { + SSLContext sslContext = serverSslContext(certificate.pkcs12()); + InetAddress loopback = InetAddress.getByName("localhost"); + HttpsServer server = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + server.createContext("/", handler); + server.start(); + servers.add(server); + return server; + } + + private static SSLContext serverSslContext(Path pkcs12Path) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(pkcs12Path)) { + keyStore.load(input, KEYSTORE_PASSWORD); + } + KeyManagerFactory keyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keyStore, KEYSTORE_PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } + + private static void respondForKubernetesRequest(HttpExchange exchange) throws IOException { + String path = exchange.getRequestURI().getRawPath(); + if ("/apis/authentication.k8s.io/v1/selfsubjectreviews".equals(path)) { + exchange.getRequestBody().readAllBytes(); + respond(exchange, 201, SELF_REVIEW); + } else if ("/api/v1/namespaces/kube-system".equals(path)) { + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE).equals(path)) { + respond(exchange, 200, TARGET_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks").equals(path)) { + respond(exchange, 200, CONFIG_MAP); + } else { + respond(exchange, 404, new byte[0]); + } + } + + private static void respond(HttpExchange exchange, int statusCode, byte[] body) + throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + if (body.length == 0) { + exchange.sendResponseHeaders(statusCode, -1); + exchange.close(); + return; + } + exchange.sendResponseHeaders(statusCode, body.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(body); + } + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(key, certificate); + } + + private static TestServerCertificate issueServerCertificate( + Path directory, TestAuthority authority, String commonName, String dnsName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + Path pkcs12 = directory.resolve(commonName + ".p12"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=serverAuth\n" + + "subjectAltName=DNS:" + + dnsName + + "\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + request.toString(), + "-subj", + "/CN=" + commonName); + runOpenSsl( + directory, + "x509", + "-req", + "-in", + request.toString(), + "-CA", + authority.certificate().toString(), + "-CAkey", + authority.privateKey().toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + runOpenSsl( + directory, + "pkcs12", + "-export", + "-out", + pkcs12.toString(), + "-inkey", + key.toString(), + "-in", + certificate.toString(), + "-certfile", + authority.certificate().toString(), + "-passout", + "pass:firemud-test"); + return new TestServerCertificate(pkcs12); + } + + private static void runOpenSsl(Path workingDirectory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(workingDirectory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException failure) { + throw new IllegalStateException("OpenSSL is required for this ephemeral HTTPS test", failure); + } + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral HTTPS certificate generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral HTTPS certificate generation failed"); + } + } + + private static String namespaceJson(String name, String uid) { + return """ + {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"}, + "status":{"phase":"Active"}} + """ + .formatted(name, uid); + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record ProtectedFiles( + Path bindingPath, + Path trustRoot, + Path caPath, + Path tokenRoot, + Path tokenPath, + Path currentToken, + AccountJwtJwksApiBinding binding) { + void projectToken(String version, String value, String fileName) throws IOException { + Path versionDirectory = Files.createDirectory(tokenRoot.resolve(version)); + Path nextToken = versionDirectory.resolve(fileName); + Files.writeString(nextToken, value, StandardCharsets.UTF_8); + applyPermissions(versionDirectory, "rwxr-xr-x"); + applyPermissions(nextToken, "r--r-----"); + Path dataLink = tokenRoot.resolve("..data"); + Files.delete(dataLink); + Files.createSymbolicLink(dataLink, Path.of(version)); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestServerCertificate(Path pkcs12) {} + + private record TestPki( + byte[] trustedCa, + byte[] untrustedCa, + TestServerCertificate trustedServer, + TestServerCertificate wrongHostnameServer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java new file mode 100644 index 0000000000..572598164b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.accountservice.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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtJwksPublicationRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String JWKS = "{\"keys\":[]}"; + private static final String MARKER = "{\"phase\":\"PREPUBLISHED\"}"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void currentReadsRemainMandatoryAccountTransactions() throws Exception { + assertMandatory("readCurrentIntent", Binding.class, TrustFence.class); + assertMandatory("readCurrentPublication", Binding.class, TrustFence.class); + assertMandatory( + "recordPrepublicationIntent", + Binding.class, + TrustFence.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationResult.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationRequest.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class); + } + + @Test + void publicationRepositoryRejectsCallsOutsideAnOwningAccountTransaction() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository repository = + new AccountJwtJwksPublicationRepository(dsl, desired); + + assertThatThrownBy(() -> repository.readCurrentIntent(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired); + } + + @Test + void snapshotAndPublicDataDigestsBindEveryObservedPublicByte() { + String first = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "preserve")); + String sameDifferentOrder = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("other.txt", "preserve", "jwks.json", JWKS)); + String changed = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "changed")); + + assertThat(first).hasSize(64).isEqualTo(sameDifferentOrder).isNotEqualTo(changed); + assertThat(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER)) + .isNotEqualTo(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER + " ")); + } + + @Test + void immutableEvidenceDigestsBindIntentReceiptAndMountedCorrespondence() { + PrepublicationIntent intent = intent(); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + MountObservation observation = MountObservation.create(intent, receipt); + + assertThat(intent.intentDigest()).isEqualTo(PrepublicationIntent.digest(intent)); + assertThat(receipt.receiptDigest()).isEqualTo(PublicationReceipt.digest(receipt)); + assertThat(observation.observationDigest()).isEqualTo(MountObservation.digest(observation)); + assertThat(observation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + } + + @Test + void immutableEvidenceRejectsChangedDigestAndNonAdvancingRemoteReadback() { + PrepublicationIntent intent = intent(); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "f".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy(() -> PublicationReceipt.create(intent, intent.expectedResourceVersion())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourceVersion did not advance"); + } + + private static PrepublicationIntent intent() { + return PrepublicationIntent.create( + OPERATION_ID, + BINDING, + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + 2L, + TRUST, + "e".repeat(64), + "api-r1", + "jwt-jwks", + "44444444-4444-4444-8444-444444444444", + "41", + "f".repeat(64), + "1", + "jwt-1-test", + "9".repeat(64), + Optional.empty(), + Optional.empty(), + JWKS, + MARKER, + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER), + sha256(MARKER)); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static void assertMandatory(String method, Class... parameterTypes) throws Exception { + Transactional transactional = + AccountJwtJwksPublicationRepository.class + .getMethod(method, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java new file mode 100644 index 0000000000..281daec872 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.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.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtReadinessProbeRepositoryTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + void requiresAnOwningAccountTransactionBeforeReadingOtherAuthorities() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + + assertThatThrownBy(() -> repository.planCurrent(BINDING, TRUST, Instant.ofEpochSecond(10_000))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void promotionProofReadsRequireWritableOwnerTransactionForLockedEvidence() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + UUID operationId = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy( + () -> repository.readCurrentPromotionPrerequisites(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + assertThatThrownBy(() -> repository.readPromotionProof(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void matrixIsCanonicalExplicitAndStillMarkedIncomplete() { + String matrix = AccountJwtReadinessProbeRepository.applicabilityMatrixJson(); + + assertThat(matrix) + .isEqualTo( + "{\"inventoryStatus\":\"PARTIAL_UNCONFIRMED\",\"schemaVersion\":1," + + "\"validators\":[{\"applicableProfiles\":[{\"audience\":\"control-ui\"," + + "\"tokenProfile\":\"control-ui\"},{\"audience\":\"player-bootstrap\"," + + "\"tokenProfile\":\"player-bootstrap\"},{\"audience\":\"account-service\"," + + "\"tokenProfile\":\"game-session-account-delegation\"}]," + + "\"validatorId\":\"account-service\"}]}"); + assertThat(matrix).doesNotContain("credential-authenticate-account"); + } + + @Test + void firstInstallFenceHasExactAbsentActiveAndPublishedPair() { + AccountJwtReadinessProbeRepository.SignerFence fence = + new AccountJwtReadinessProbeRepository.SignerFence(Optional.empty(), Optional.empty()); + + assertThat(fence.durableActive()).isEmpty(); + assertThat(fence.publishedActive()).isEmpty(); + assertThatThrownBy( + () -> + new AccountJwtReadinessProbeRepository.SignerFence( + Optional.empty(), + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) + .isInstanceOf(AccountJwtReadinessProbeRepository.QuarantinedStateException.class); + } + + @Test + void plannedFirstInstallEntryCarriesAnAbsentPreviousActiveFence() { + var entry = + new AccountJwtReadinessProbeRepository.ProbeEntry( + UUID.randomUUID(), + "a".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle + .ProbeKind.REPRESENTATIVE, + UUID.randomUUID(), + "1", + "first-key", + Optional.empty(), + 1, + 1, + 20_000, + 20_300, + AccountJwtReadinessProbeRepository.ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.PLANNED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java new file mode 100644 index 0000000000..cddf5dd5c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -0,0 +1,748 @@ +package net.firedevops.firemud.accountservice.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.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.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerDesiredStateRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "binding-r1"); + private static final UUID SECRET_UID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final EnrollmentIdentity ENROLLMENT = + new EnrollmentIdentity( + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "12", + "c".repeat(64)); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception { + assertMandatory("initialize", Binding.class, EnrollmentIdentity.class); + assertMandatory("read", Binding.class); + assertMandatory("ensureCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory("readCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory( + "recordSecretObservation", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class); + assertMandatory( + "recordGenerationResult", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class, + String.class, + String.class); + assertMandatoryWritable("readPreparedGenerationForRecovery", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readAndMarkPreparedPromotionDispatched", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readCurrentCommittedSigner", Binding.class, TrustFence.class, String.class, String.class); + assertMandatoryWritable( + "commitPreparedPromotion", + Binding.class, + TrustFence.class, + UUID.class, + ReadinessPromotionProof.class); + assertMandatoryWritable( + "prepareCurrentGeneration", + Binding.class, + TrustFence.class, + PromotionPreparation.class, + ReadinessPromotionProof.class); + } + + @Test + void promotionCommitRequiresOwnerCreatedReadinessProofBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.commitPreparedPromotion( + BINDING, + TRUST, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("readiness proof"); + verifyNoInteractions(dsl); + } + + @Test + void lockedPromotionReadsRejectReadOnlyTransactionsBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readPreparedGenerationForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + assertThatThrownBy(() -> repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void accountCreatesAndReplaysOnlyItsOwnBoundGenerationRequest() { + Conversation conversation = new Conversation(); + + GenerationRequest first = inWritableTransaction(conversation::ensureRequest); + GenerationRequest retry = inWritableTransaction(conversation::ensureRequest); + + assertThat(first).isEqualTo(retry); + assertThat(first.phase()).isEqualTo(GenerationPhase.OBSERVE_PRIVATE_SECRET); + assertThat(first.operationId().version()).isEqualTo(4); + assertThat(first.operationDigest()).hasSize(64); + assertThat(first.desiredStateVersion()).isEqualTo(2); + assertThat(first.targetGeneration()).isEqualTo("1"); + assertThat(first.targetKid()).startsWith("jwt-1-"); + assertThat(first.expectedActive()).isEmpty(); + assertThat(first.expectedPublishedActive()).isEmpty(); + assertThat(first.privateSecretName()).isEqualTo("jwt-signing-keys"); + assertThat(first.expectedSecretResourceVersion()).isEmpty(); + assertThat(first.publicKeyFingerprint()).isEmpty(); + assertThat(first.publicJwkJson()).isEmpty(); + assertThat(conversation.operationInsert).isNotNull(); + assertThat(conversation.executedStatements) + .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")) + .anyMatch(sql -> sql.contains("generation_operation_id")) + .noneMatch(sql -> sql.contains("target_public_key_fingerprint")); + verify(conversation.dsl, times(2)).execute(anyString(), any(Object[].class)); + } + + @Test + void generationRequestDefensivelyCopiesItsValidatedPrivateSlots() { + Conversation conversation = new Conversation(); + GenerationRequest source = inWritableTransaction(conversation::ensureRequest); + List suppliedSlots = new ArrayList<>(source.allowedPrivateSlots()); + + GenerationRequest copied = + new GenerationRequest( + source.phase(), + source.operationId(), + source.operationDigest(), + source.generationRequestDigest(), + source.desiredStateVersion(), + source.binding(), + source.trustFence(), + source.privateSecretName(), + source.targetGeneration(), + source.targetKid(), + source.targetAlgorithm(), + source.operationAction(), + suppliedSlots, + source.expectedActive(), + source.expectedPublishedActive(), + source.secretUid(), + source.expectedSecretResourceVersion(), + source.generationReceiptDigest(), + source.publicKeyFingerprint(), + source.publicJwkJson(), + source.observedSecretResourceVersion()); + + suppliedSlots.clear(); + + assertThat(copied.allowedPrivateSlots()).containsExactly("pending"); + assertThatThrownBy(() -> copied.allowedPrivateSlots().add("current")) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void committedActiveSignerNeedsAnExplicitDurableRotationRequest() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Map values = new HashMap<>(); + values.put("environment_id", BINDING.environmentId()); + values.put("cluster_id", BINDING.clusterId()); + values.put("kubernetes_namespace", BINDING.namespace()); + values.put("custody_mode", BINDING.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", 8L); + values.put("durable_active_generation", 4L); + values.put("durable_active_kid", "jwt-4-active"); + values.put("published_active_generation", 4L); + values.put("published_active_kid", "jwt-4-active"); + values.put("generation_operation_id", null); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(TRUST.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(TRUST.expectedNamespaceUid())); + values.put("enrollment_materializer_binding_digest", TRUST.bindingDigest()); + values.put("enrollment_materializer_config_revision", TRUST.configRevision()); + values.put("enrollment_api_binding_digest", "b".repeat(64)); + values.put("enrollment_api_config_revision", "api-r1"); + values.put( + "enrollment_public_config_map_uid", + UUID.fromString("33333333-3333-4333-8333-333333333333")); + values.put("enrollment_public_config_map_resource_version", "12"); + values.put("enrollment_public_config_map_snapshot_digest", "c".repeat(64)); + Record activeState = record(values); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(activeState); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessageContaining("durable rotation request"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflicts() { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + GenerationRequest replay = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + + assertThat(pending.phase()).isEqualTo(GenerationPhase.GENERATE_PENDING); + assertThat(pending.generationRequestDigest()).hasSize(64); + assertThat(pending.secretUid()).isEqualTo(SECRET_UID.toString()); + assertThat(pending.expectedSecretResourceVersion()).isEqualTo("12"); + assertThat(pending.publicKeyFingerprint()).isEmpty(); + assertThat(replay).isEqualTo(pending); + int executedBeforeConflict = conversation.executedStatements.size(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "changed-rv"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeConflict); + } + + @Test + void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + GenerationResult replay = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + + assertThat(result).isEqualTo(replay); + assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(result.expectedPriorResourceVersion()).isEqualTo("12"); + assertThat(result.observedResourceVersion()).isEqualTo("13"); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + int executedBeforePromotionAttempt = conversation.executedStatements.size(); + PromotionPreparation callerSuppliedPreparation = + new PromotionPreparation( + result.operationId(), + result, + ENROLLMENT, + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "14", + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + "1".repeat(64), + "2".repeat(64), + "{\"keys\":[" + result.publicJwkJson() + "]}"); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.prepareCurrentGeneration( + BINDING, TRUST, callerSuppliedPreparation, null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account-verified readiness proof is required"); + assertThat(conversation.executedStatements).hasSize(executedBeforePromotionAttempt); + } + + @Test + void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { + DSLContext emptyDsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository emptyRepository = + new AccountJwtSignerDesiredStateRepository(emptyDsl); + Record emptyState = stateRow(BINDING, 1, null, null, null, null, null); + when(emptyDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(emptyState); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class); + verify(emptyDsl, never()).execute(anyString(), any(Object[].class)); + + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + UUID wrongOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); + int executedBeforeStaleCall = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + wrongOperation, + operation.operationDigest(), + SECRET_UID.toString(), + "12"))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeStaleCall); + } + + @Test + void privateOrMalformedPublicJwkIsRejectedBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.recordGenerationResult( + BINDING, + TRUST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "a".repeat(64), + SECRET_UID.toString(), + "12", + "13", + "{\"d\":\"private\"}"))) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void initializationStaysExplicitAndNonAuthorizing() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Record initializedState = stateRow(BINDING, 1, null, null, null, null, null); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(initializedState); + + var state = inWritableTransaction(() -> repository.initialize(BINDING, ENROLLMENT)); + + assertThat(state.recordVersion()).isEqualTo(1); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(sql.capture(), bindings.capture()); + assertThat(sql.getValue()) + .contains("generation_operation_id") + .contains("prepared_operation_id"); + Object[] values = bindings.getValue(); + assertThat(values[4]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + assertThat(values[5]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + assertThat(values[10]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.publicConfigMapUid())); + } + + private void assertMandatory(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + + private void assertMandatoryWritable(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transactional.readOnly()).isFalse(); + } + + private static Record stateRow( + Binding binding, + long version, + Long durableGeneration, + String durableKid, + Long publishedGeneration, + String publishedKid, + UUID generationOperationId) { + Map values = new HashMap<>(); + values.put("environment_id", binding.environmentId()); + values.put("cluster_id", binding.clusterId()); + values.put("kubernetes_namespace", binding.namespace()); + values.put("custody_mode", binding.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", version); + values.put("durable_active_generation", durableGeneration); + values.put("durable_active_kid", durableKid); + values.put("published_active_generation", publishedGeneration); + values.put("published_active_kid", publishedKid); + values.put("generation_operation_id", generationOperationId); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + values.put( + "enrollment_materializer_binding_digest", ENROLLMENT.materializerTrustBindingDigest()); + values.put( + "enrollment_materializer_config_revision", ENROLLMENT.materializerTrustConfigRevision()); + values.put("enrollment_api_binding_digest", ENROLLMENT.apiBindingDigest()); + values.put("enrollment_api_config_revision", ENROLLMENT.apiConfigRevision()); + values.put( + "enrollment_public_config_map_uid", UUID.fromString(ENROLLMENT.publicConfigMapUid())); + values.put( + "enrollment_public_config_map_resource_version", + ENROLLMENT.publicConfigMapResourceVersion()); + values.put( + "enrollment_public_config_map_snapshot_digest", ENROLLMENT.publicConfigMapSnapshotDigest()); + return record(values); + } + + private static Record generationOperationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest_version", 1); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_previous_generation", parameters[7]); + values.put("expected_previous_kid", parameters[8]); + values.put("expected_published_generation", parameters[9]); + values.put("expected_published_kid", parameters[10]); + values.put("target_generation", parameters[11]); + values.put("target_kid", parameters[12]); + values.put("target_algorithm", parameters[13]); + values.put("expected_cluster_incarnation_uid", parameters[14]); + values.put("expected_namespace_uid", parameters[15]); + values.put("trust_binding_digest", parameters[16]); + values.put("trust_config_revision", parameters[17]); + values.put("operation_action", "MATERIALIZE_PENDING"); + values.put("allowed_private_slots_canonical_bytes", parameters[18]); + return record(values); + } + + private static Record secretObservationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_cluster_incarnation_uid", parameters[7]); + values.put("expected_namespace_uid", parameters[8]); + values.put("trust_binding_digest", parameters[9]); + values.put("trust_config_revision", parameters[10]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[11]); + values.put("observed_resource_version", parameters[12]); + values.put("observation_digest", parameters[13]); + values.put("generation_request_digest", parameters[14]); + return record(values); + } + + private static Record generationResultRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("generation_request_digest", parameters[6]); + values.put("desired_state_version", parameters[7]); + values.put("expected_cluster_incarnation_uid", parameters[8]); + values.put("expected_namespace_uid", parameters[9]); + values.put("trust_binding_digest", parameters[10]); + values.put("trust_config_revision", parameters[11]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[12]); + values.put("expected_prior_resource_version", parameters[13]); + values.put("observed_resource_version", parameters[14]); + values.put("target_generation", parameters[15]); + values.put("target_kid", parameters[16]); + values.put("target_algorithm", "RS256"); + values.put("public_key_fingerprint", parameters[17]); + values.put("public_jwk_json", parameters[18]); + values.put("receipt_digest", parameters[19]); + return record(values); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new java.util.TreeMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, fingerprint); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Record record(Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + return row; + } + + private static T inWritableTransaction(java.util.function.Supplier operation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private record PublicJwk(String json, String fingerprint) {} + + private final class Conversation { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + private final List executedStatements = new java.util.ArrayList<>(); + private Object[] operationInsert; + private Object[] observationInsert; + private Object[] resultInsert; + private int stateReadCount; + + private Conversation() { + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + Object[] arguments = invocation.getArguments(); + Object[] parameters = + arguments.length == 2 && arguments[1] instanceof Object[] bindings + ? bindings + : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); + executedStatements.add(sql); + if (sql.contains("account_jwt_signer_generation_operations")) { + operationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_secret_observations")) { + observationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_generation_results")) { + resultInsert = parameters.clone(); + } + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_jwt_signer_desired_states")) { + return stateReadCount++ == 0 + ? stateRow(BINDING, 1, null, null, null, null, null) + : stateRow( + BINDING, + 2, + null, + null, + null, + null, + operationInsert == null ? null : (UUID) operationInsert[0]); + } + if (sql.contains("account_jwt_signer_generation_operations")) { + return operationInsert == null ? null : generationOperationRow(operationInsert); + } + if (sql.contains("account_jwt_signer_generation_results")) { + return resultInsert == null ? null : generationResultRow(resultInsert); + } + if (sql.contains("account_jwt_signer_secret_observations")) { + return observationInsert == null ? null : secretObservationRow(observationInsert); + } + return null; + }); + } + + private GenerationRequest ensureRequest() { + return repository.ensureCurrentGenerationRequest(BINDING, TRUST); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java new file mode 100644 index 0000000000..a2729f4554 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -0,0 +1,890 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.OriginalCommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiCurrentActorVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Full verifier unit proof. Owner repositories and protected signer/JWKS bindings are mocked at + * their public seams; this does not claim physical PostgreSQL, Redis, or Kubernetes integration + * authority. + */ +class AccountControlUiCurrentActorVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ISSUER = "firemud-account-service"; + private static final String KID = "control-ui-key"; + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final UUID ACCOUNT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("10000000-0000-4000-8000-000000000009"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID OTHER_TENANT_ID = + UUID.fromString("20000000-0000-4000-8000-000000000009"); + private static final UUID TOKEN_ID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID OPERATION_ID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID REQUEST_ID = UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("60000000-0000-4000-8000-000000000006"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("80000000-0000-4000-8000-000000000008"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("90000000-0000-4000-8000-000000000009"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PROMOTION_REQUEST_DIGEST = "b".repeat(64); + private static final String PRIVATE_RECEIPT_DIGEST = "c".repeat(64); + private static final String PUBLIC_RECEIPT_DIGEST = "d".repeat(64); + private static final String API_BINDING_DIGEST = "e".repeat(64); + private static final String API_CA_DIGEST = "f".repeat(64); + private static final Instant NOW = Instant.parse("2035-04-05T06:07:08Z"); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final long EXPIRY_SECONDS = NOW_SECONDS + 300L; + private static KeyPair signingKey; + + @BeforeAll + static void generateSigningKey() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signingKey = generator.generateKeyPair(); + } + + @Test + void verifiesARealSignedTokenAgainstExactCommittedRegistrySignerAndCurrentTenantEvidence() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + AccountControlUiCurrentActorVerifier.CurrentActor actor = + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + assertThat(actor.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(actor.tenantId()).isEqualTo(TENANT_ID); + assertThat(actor.issuanceOperationId()).isEqualTo(OPERATION_ID); + assertThat(actor.tokenHash()).isEqualTo(fixture.tokenHash); + assertThat(actor.currentTenantRoles()).containsExactly("tenantAdmin"); + assertThat(actor.issuerGeneration()).isEqualTo(1L); + assertThat(actor.accountGeneration()).isEqualTo(1L); + assertThat(actor.tenantGeneration()).isEqualTo(1L); + assertThat(actor.membershipGeneration()).isEqualTo(1L); + assertThat(actor.membershipVersion()).isEqualTo(1L); + assertThat(actor.issuanceFence()).isEqualTo(1L); + verify(fixture.signerStates) + .readOriginalCommittedSigner( + eq(fixture.signerBinding), + eq(fixture.trustFence), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID)); + } + + @Test + void rejectsAChangedActorEvenWhenThePresentedCompactTokenIsValidlySigned() throws Exception { + Fixture fixture = new Fixture(OTHER_ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.issuances).readCommitted(fixture.tokenHash); + verify(fixture.membershipPairs, never()).readPositive(OTHER_ACCOUNT_ID, TENANT_ID); + } + + @Test + void rejectsASelectedTenantOutsideTheExactSignedTenantScope() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, OTHER_TENANT_ID)); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + @Test + void rejectsStaleTenantGenerationEvenWhenTheCurrentTenantEventAgreesWithTheOwnerSnapshot() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 2, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsStaleMembershipGenerationAgainstTheCurrentPositivePairAndEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 2, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsRoleSnapshotThatDiffersFromTheCurrentMembershipEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("moderator"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsARevokedIssuanceWhenNoCommittedIssuanceCanBeRead() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + when(fixture.issuances.readCommitted(fixture.tokenHash)).thenReturn(Optional.empty()); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.sourceEvidence, never()).readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID); + } + + @Test + void rejectsACommitRecordWithAnInvalidCoordinationReadbackReceipt() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 0, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsACommittedSignerReceiptThatDoesNotMatchProtectedOriginalReadback() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, true); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsGlobalRoleClaimsInsteadOfTreatingThemAsTenantOperatorAuthority() throws Exception { + Fixture fixture = + new Fixture(ACCOUNT_ID, List.of("platformAdmin"), 1, 1, List.of("tenantAdmin"), 1, false); + + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + private static void assertDenied(Runnable action) { + assertThatThrownBy(action::run).isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + private final UUID issuanceAccountId = ACCOUNT_ID; + private final String compactJwt; + private final String tokenHash; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountControlUiCurrentActorVerifier verifier; + private final AccountControlUiCommittedIssuanceRepository issuances = + mock(AccountControlUiCommittedIssuanceRepository.class); + private final AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountTenantAuthorityEventRepository tenantEvents = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountMembershipPairAuthorityRepository membershipPairs = + mock(AccountMembershipPairAuthorityRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + private final AccountAuthorityOutboxRepository outbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountJwtSignerDesiredStateRepository signerStates = + mock(AccountJwtSignerDesiredStateRepository.class); + + private Fixture( + UUID tokenAccountId, + List globalRoles, + long currentTenantGeneration, + long currentMembershipGeneration, + List roleSnapshot, + int localAofCount, + boolean mismatchPublicReceipt) + throws Exception { + Map claims = claims(tokenAccountId, globalRoles); + compactJwt = sign(claims, signingKey); + tokenHash = sha256(compactJwt.getBytes(StandardCharsets.US_ASCII)); + + String jwksJson = jwks((RSAPublicKey) signingKey.getPublic()); + byte[] jwksBytes = jwksJson.getBytes(StandardCharsets.UTF_8); + SourceIdentity sourceIdentity = sourceIdentity(); + PublicJwksSnapshot jwksSnapshot = new PublicJwksSnapshot(sourceIdentity, jwksBytes); + AccountJwtJwksTrustedSource publicJwks = mock(AccountJwtJwksTrustedSource.class); + when(publicJwks.sourceIdentity()).thenReturn(sourceIdentity); + when(publicJwks.load()).thenReturn(jwksSnapshot); + + String trustBindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64))); + Binding materializerBinding = + new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64)), + "trust-r1", + trustBindingDigest); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + + ParsedBinding apiParsedBinding = + new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/test/serving-ca.pem"), + API_CA_DIGEST, + Path.of("/test/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:" + NAMESPACE + ":account-service", + API_BINDING_DIGEST); + when(apiBinding.current()).thenReturn(apiParsedBinding); + + AccountJwtSignerDesiredStateRepository.CustodyMode custodyMode = + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK; + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, custodyMode); + trustFence = new TrustFence(CLUSTER_UID, NAMESPACE_UID, trustBindingDigest, "trust-r1"); + + byte[] sourceBytes = + canonicalBytes( + Map.of( + "schemaVersion", 1, + "issuer", ISSUER, + "accountId", issuanceAccountId.toString(), + "tenantId", TENANT_ID.toString(), + "sources", List.of())); + String sourceHash = sha256(sourceBytes); + Map bundleRef = + Map.of( + "bundleVersion", "1", + "sourceVersion", "1", + "sourceFence", "1", + "linearization", "1"); + Map operation = + Map.of( + "operationId", OPERATION_ID.toString(), + "requestId", REQUEST_ID.toString(), + "requestDigest", REQUEST_DIGEST, + "callerWorkload", "logging-admin-service", + "callerContextId", CALLER_CONTEXT_ID.toString(), + "accountId", issuanceAccountId.toString()); + Map sourceVersions = sourceVersions(); + Map roleEvidence = + Map.of("scopedRoles", claims.get("scopedRoles"), "freshnessSource", sourceHash); + Map bundle = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schema", "account-auth-evidence-bundle/v1"), + Map.entry("bundleRef", bundleRef), + Map.entry("snapshotIdentity", sourceHash), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry( + "scope", + Map.of( + "kind", "TENANT", + "accountId", issuanceAccountId.toString(), + "tenantIds", List.of(TENANT_ID.toString()))), + Map.entry("operation", operation), + Map.entry("tokenIdentity", tokenIdentity(claims)), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", claims.get("issuanceFence")), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry( + "accountIdentitySource", + Map.of( + "accountId", + issuanceAccountId.toString(), + "source", + "account_repository_insert", + "sourceVersion", + 1)), + Map.entry( + "outboxCheckpoints", + Map.of( + "issuer", 0, + "account", 0, + "tenant", 0, + "membership", 1)), + Map.entry("roleEvidence", roleEvidence))); + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceHash); + bundle.put("evaluationIdentity", sha256(canonicalBytes(evaluation))); + byte[] bundleBytes = canonicalBytes(bundle); + + String fingerprint = publicKeyFingerprint((RSAPublicKey) signingKey.getPublic()); + String publicDataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + jwksJson, "{\"generation\":\"1\",\"kid\":\"" + KID + "\"}"); + byte[] signerReceipt = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-control-ui-committed-signer/v1"), + Map.entry("environmentId", ENVIRONMENT), + Map.entry("clusterId", CLUSTER), + Map.entry("namespace", NAMESPACE), + Map.entry("clusterIncarnationUid", CLUSTER_UID), + Map.entry("namespaceUid", NAMESPACE_UID), + Map.entry("trustBindingDigest", trustBindingDigest), + Map.entry("trustConfigRevision", "trust-r1"), + Map.entry("apiBindingDigest", API_BINDING_DIGEST), + Map.entry("apiConfigRevision", "api-r1"), + Map.entry("promotionOperationId", PROMOTION_OPERATION_ID.toString()), + Map.entry("promotionRequestDigest", PROMOTION_REQUEST_DIGEST), + Map.entry("generationOperationId", GENERATION_OPERATION_ID.toString()), + Map.entry("signerGeneration", "1"), + Map.entry("kid", KID), + Map.entry("algorithm", "RS256"), + Map.entry("publicKeyFingerprint", fingerprint), + Map.entry("privateReceiptDigest", PRIVATE_RECEIPT_DIGEST), + Map.entry("privateResourceVersion", "22"), + Map.entry("publicReceiptDigest", PUBLIC_RECEIPT_DIGEST), + Map.entry("publicResourceVersion", "23"), + Map.entry("publicConfigMapUid", CONFIG_MAP_UID), + Map.entry("publicDataDigest", publicDataDigest))); + + Map authBundleReference = new LinkedHashMap<>(bundleRef); + authBundleReference.put("canonicalSha256", sha256(bundleBytes)); + Map activeRegistryRecord = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", tokenHash), + Map.entry("kid", KID), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", issuanceAccountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", 1), + Map.entry("operationId", OPERATION_ID.toString()), + Map.entry("requestId", REQUEST_ID.toString()), + Map.entry("requestDigest", REQUEST_DIGEST), + Map.entry("state", "active"), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry("authEvidenceBundle", authBundleReference), + Map.entry("originalSignerReceiptDigest", sha256(signerReceipt)))); + byte[] activeRegistry = canonicalBytes(activeRegistryRecord); + Map pendingRegistryRecord = new LinkedHashMap<>(activeRegistryRecord); + pendingRegistryRecord.put("state", "pending"); + pendingRegistryRecord.put("registryVersion", 1); + byte[] pendingRegistry = canonicalBytes(pendingRegistryRecord); + byte[] pendingReceipt = + canonicalBytes( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + tokenHash, + "recordDigest", + sha256(pendingRegistry), + "expiryMillis", + Math.multiplyExact(EXPIRY_SECONDS, 1000L), + "aclIdentity", + "account_coord_app", + "localAofCount", + localAofCount, + "replicaAofCount", + 1)); + + var committedIssuance = mock(CommittedIssuance.class); + when(committedIssuance.requestId()).thenReturn(REQUEST_ID); + when(committedIssuance.operationId()).thenReturn(OPERATION_ID); + when(committedIssuance.tokenJti()).thenReturn(TOKEN_ID); + when(committedIssuance.accountId()).thenReturn(issuanceAccountId); + when(committedIssuance.tenantId()).thenReturn(TENANT_ID); + when(committedIssuance.callerWorkload()).thenReturn("logging-admin-service"); + when(committedIssuance.callerContextId()).thenReturn(CALLER_CONTEXT_ID); + when(committedIssuance.requestDigest()).thenReturn(REQUEST_DIGEST); + when(committedIssuance.claims()).thenReturn(canonicalBytes(claims)); + when(committedIssuance.source()).thenReturn(sourceBytes); + when(committedIssuance.bundle()).thenReturn(bundleBytes); + when(committedIssuance.signerReceipt()).thenReturn(signerReceipt); + when(committedIssuance.issuedAtEpochSecond()).thenReturn(NOW_SECONDS); + when(committedIssuance.expiresAtEpochSecond()).thenReturn(EXPIRY_SECONDS); + when(committedIssuance.expiryMillis()).thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + when(committedIssuance.status()).thenReturn("COMMITTED"); + when(committedIssuance.tokenHash()).thenReturn(tokenHash); + when(committedIssuance.pendingRegistry()).thenReturn(pendingRegistry); + when(committedIssuance.activeRegistry()).thenReturn(activeRegistry); + when(committedIssuance.pendingReceipt()).thenReturn(pendingReceipt); + when(issuances.readCommitted(tokenHash)).thenReturn(Optional.of(committedIssuance)); + + configureSignerReadback(mismatchPublicReceipt ? "0".repeat(64) : publicDataDigest); + configureRegistry(activeRegistry); + configureCurrentSources(currentTenantGeneration, currentMembershipGeneration, roleSnapshot); + + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + verifier = + new AccountControlUiCurrentActorVerifier( + publicJwks, + signerStates, + materializerTrust, + apiBinding, + registry, + issuances, + sourceEvidence, + generations, + tenantEvents, + memberships, + membershipPairs, + roleSnapshots, + outbox, + transactionManager, + Clock.fixed(NOW, ZoneId.of("UTC"))); + } + + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private AccountControlUiRegistryReader registry; + + private void configureSignerReadback(String originalPublicDataDigest) throws Exception { + var original = mock(OriginalCommittedSignerEvidence.class); + var promotion = mock(PromotionOperationEvidence.class); + var generation = mock(GenerationResult.class); + var privateReceipt = mock(PrivatePromotionReceipt.class); + var publicReceipt = mock(ActiveJwksPromotionReceipt.class); + when(original.promotion()).thenReturn(promotion); + when(original.generationResult()).thenReturn(generation); + when(original.privateReceipt()).thenReturn(privateReceipt); + when(original.publicReceipt()).thenReturn(publicReceipt); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.operationId()).thenReturn(PROMOTION_OPERATION_ID); + when(promotion.requestDigest()).thenReturn(PROMOTION_REQUEST_DIGEST); + when(promotion.generationOperationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.operationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.targetKid()).thenReturn(KID); + when(generation.targetGeneration()).thenReturn("1"); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()) + .thenReturn(publicKeyFingerprint((RSAPublicKey) signingKey.getPublic())); + when(privateReceipt.receiptDigest()).thenReturn(PRIVATE_RECEIPT_DIGEST); + when(privateReceipt.observedResourceVersion()).thenReturn("22"); + when(publicReceipt.receiptDigest()).thenReturn(PUBLIC_RECEIPT_DIGEST); + when(publicReceipt.observedResourceVersion()).thenReturn("23"); + when(publicReceipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(publicReceipt.publicDataDigest()).thenReturn(originalPublicDataDigest); + when(signerStates.readOriginalCommittedSigner( + any(), + any(), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID))) + .thenReturn(Optional.of(original)); + } + + private void configureRegistry(byte[] activeRegistry) { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(activeRegistry); + when(commands.pexpiretime(any(byte[].class))) + .thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + registry = new AccountControlUiRegistryReader(() -> connection); + } + + private void configureCurrentSources( + long currentTenantGeneration, + long currentMembershipGeneration, + List currentRoleSnapshot) { + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 1L, 1L); + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + CurrentSourceEvidence issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1L, + 1L, + null, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + issuerStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + fence, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + accountStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 77L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 77L, + 77L); + IssuerAccountSourceSnapshot sourceSnapshot = + new IssuerAccountSourceSnapshot(issuerSource, accountSource, fence); + when(sourceEvidence.readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID)) + .thenReturn(sourceSnapshot); + + ScopeState issuerState = new ScopeState(AuthorityScope.issuer(ISSUER), 1L, 1L, null); + ScopeState accountState = new ScopeState(AuthorityScope.account(ACCOUNT_ID), 1L, 1L, fence); + ScopeState tenantState = + new ScopeState( + AuthorityScope.tenant(TENANT_ID), + currentTenantGeneration, + currentTenantGeneration, + null); + ScopeState membershipState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + currentMembershipGeneration, + currentMembershipGeneration, + fence); + CompositeSnapshot composite = + new CompositeSnapshot( + issuerState, accountState, List.of(tenantState), List.of(membershipState), fence); + when(generations.readCompositeSnapshot( + eq(ISSUER), eq(ACCOUNT_ID), eq(List.of(TENANT_ID)), eq(List.of(TENANT_ID)))) + .thenReturn(composite); + + TenantAuthorityEventV1Codec.Event tenantEvent = mock(TenantAuthorityEventV1Codec.Event.class); + when(tenantEvent.tenantId()).thenReturn(TENANT_ID); + when(tenantEvent.tenantAuthorityGeneration()).thenReturn(currentTenantGeneration); + when(tenantEvent.tenantAuthoritySourceVersion()).thenReturn(currentTenantGeneration); + when(tenantEvents.readCurrentByTenant(TENANT_ID)).thenReturn(tenantEvent); + + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("a0000000-0000-4000-8000-00000000000a"), + "sha256:" + "9".repeat(64)); + MembershipEvent membershipEvent = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + currentTenantGeneration, currentMembershipGeneration, List.of("tenantAdmin"))); + PairAuthority pair = + new PairAuthority( + ACCOUNT_ID, + TENANT_ID, + provenance, + true, + 1L, + currentMembershipGeneration, + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + false); + when(membershipPairs.readPositive(ACCOUNT_ID, TENANT_ID)).thenReturn(Optional.of(pair)); + + Account account = new Account(); + account.setId(101L); + account.setAccountUuid(ACCOUNT_ID); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(202L); + membership.setAccount(account); + membership.setTenantUuid(TENANT_ID); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(currentMembershipGeneration); + when(memberships.findFreshMembership(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(membership)); + RoleSnapshot roles = + new RoleSnapshot( + 101L, null, 202L, 1L, currentRoleSnapshot, ACCOUNT_ID, TENANT_ID, provenance); + when(roleSnapshots.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, provenance, 202L, 1L)) + .thenReturn(Optional.of(roles)); + + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID; + AccountAuthorityOutboxRepository.Event membershipOutboxEvent = + new AccountAuthorityOutboxRepository.Event( + streamKey, + membershipEvent.requestId(), + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(membershipOutboxEvent)); + } + } + + private static Map claims(UUID accountId, List globalRoles) { + Map authorityTuple = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "privateRealmGrantVersions", List.of())); + Map claims = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("iss", ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("aud", "control-ui"), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", authorityTuple), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 1)), + Map.entry("issuanceFence", 1), + Map.entry("scopedRoles", Map.of(TENANT_ID.toString(), List.of("tenantAdmin"))))); + if (globalRoles != null) { + claims.put("globalRoles", globalRoles); + } + return claims; + } + + private static Map membershipEventPreimage( + long tenantGeneration, long membershipGeneration, List roles) { + String sourceScope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + String streamKey = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + Map tuple = + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(tenantGeneration)), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(membershipGeneration)), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("requestId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", sourceScope), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), "1")), + Map.entry("membershipAuthorityGeneration", Long.toString(membershipGeneration)), + Map.entry("authorityTuple", tuple), + Map.entry("issuanceFence", "1"), + Map.entry("roles", roles), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false)); + } + + private static Map tokenIdentity(Map claims) { + return Map.of( + "jti", claims.get("jti"), + "tokenGeneration", claims.get("tokenGeneration"), + "iat", claims.get("iat"), + "nbf", claims.get("nbf"), + "exp", claims.get("exp")); + } + + private static Map sourceVersions() { + return Map.of( + "ISSUER:" + ISSUER, 1, + "ACCOUNT:" + ACCOUNT_ID, 1, + "TENANT:" + TENANT_ID, 1, + "MEMBERSHIP:" + ACCOUNT_ID + ":" + TENANT_ID, 1); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + API_CA_DIGEST); + } + + private static String jwks(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + return JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + KID, + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + } + + private static String publicKeyFingerprint(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + byte[] canonical = canonicalBytes(Map.of("e", exponent, "kty", "RSA", "n", modulus)); + return sha256(canonical); + } + + private static byte[] unsigned(byte[] value) { + return value.length > 1 && value[0] == 0 + ? java.util.Arrays.copyOfRange(value, 1, value.length) + : value; + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + byte[] header = canonicalBytes(Map.of("alg", "RS256", "kid", KID, "typ", "JWT")); + byte[] payload = canonicalBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String signingInput = encoder.encodeToString(header) + "." + encoder.encodeToString(payload); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encoder.encodeToString(signature.sign()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java new file mode 100644 index 0000000000..6216b465c2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountControlUiRegistryReaderTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String TOKEN_HASH = "a".repeat(64); + + @Test + void acceptsOnlyTheExactCanonicalActiveProfileRecord() throws Exception { + byte[] bytes = canonicalRecord(); + + var parsed = AccountControlUiRegistryReader.parseActiveRecord(bytes, TOKEN_HASH); + + assertThat(parsed).containsEntry("tokenHash", TOKEN_HASH).containsEntry("state", "active"); + } + + @Test + void rejectsUnknownFieldsAndNonCanonicalBytes() throws Exception { + Map extended = new LinkedHashMap<>(record()); + extended.put("unexpected", true); + byte[] withUnknown = canonicalBytes(extended); + + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(withUnknown, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + + String canonical = new String(canonicalRecord(), StandardCharsets.UTF_8); + byte[] nonCanonical = (" " + canonical).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(nonCanonical, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void readsOnlyAfterLiveAclIdentityAndExactExpiryReadback() throws Exception { + byte[] active = canonicalRecord(); + long deadline = 1_800_000_000_000L; + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(active); + when(commands.pexpiretime(any(byte[].class))).thenReturn(deadline); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + byte[] observed = new AccountControlUiRegistryReader(provider).readActive(TOKEN_HASH); + + assertThat(observed).isEqualTo(active).isNotSameAs(active); + verify(commands).aclWhoami(); + verify(commands).pexpiretime(any(byte[].class)); + } + + @Test + void deniesWhenPhysicalExpiryDiffersFromExactTokenExpiry() throws Exception { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(canonicalRecord()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(1_800_000_300_000L); + + AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); + + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void computesExactTokenExpiryWithCheckedArithmetic() { + assertThat(AccountControlUiRegistryReader.checkedExpiryMillis(1_800_000_000L)) + .isEqualTo(1_800_000_000_000L); + assertThatThrownBy(() -> AccountControlUiRegistryReader.checkedExpiryMillis(Long.MAX_VALUE)) + .isInstanceOf(IllegalStateException.class); + } + + private static Map record() { + Map tuple = + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "membershipAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", TOKEN_HASH), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", UUID.fromString("30000000-0000-4000-8000-000000000003").toString()), + Map.entry("iat", 1_799_999_700), + Map.entry("nbf", 1_799_999_700), + Map.entry("exp", 1_800_000_000), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", tuple), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", "50000000-0000-4000-8000-000000000005"), + Map.entry("requestDigest", "b".repeat(64)), + Map.entry("state", "active"), + Map.entry( + "authoritySourceVersions", Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry( + "authEvidenceBundle", + Map.of( + "bundleVersion", + "1", + "sourceVersion", + "1", + "sourceFence", + "1", + "linearization", + "1", + "canonicalSha256", + "c".repeat(64))), + Map.entry("originalSignerReceiptDigest", "d".repeat(64))); + } + + private static byte[] canonicalRecord() throws Exception { + return canonicalBytes(record()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java new file mode 100644 index 0000000000..c38bb11fe1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -0,0 +1,591 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ApiSession; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasConflictException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.Outcome; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ResourceMissingException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksConfigMapClientTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String TARGET_NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String JWKS_OLD = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"old\"}]}"; + private static final String JWKS_NEW = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"new\"}]}"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @org.junit.jupiter.api.Test + void observesOnlyFixedConfigMapAfterPrincipalAndNamespaceChecks() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("41"); + assertThat(observed.data()).containsEntry("unrelated.txt", "retain"); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.calls) + .allMatch( + call -> + Set.of( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP, + ApiCall.PATCH_JWKS_CONFIG_MAP) + .contains(call)); + } + + @org.junit.jupiter.api.Test + void absentPrecreatedConfigMapFailsWithoutCreateOrWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.resourceExists = false; + AccountJwtJwksConfigMapClient client = client(api); + + assertThatThrownBy(client::observe).isInstanceOf(ResourceMissingException.class); + + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void oversizedConfigMapResponseIsRejectedAtTheBound() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.oversizedConfigMapResponse = true; + + assertThatThrownBy(() -> client(api).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.ApiFailureException.class); + + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void rejectsWrongAccountPrincipalAndEitherNamespaceIncarnationBeforeConfigMapRead() { + FakeKubernetesApi wrongPrincipal = new FakeKubernetesApi(); + wrongPrincipal.authenticatedUsername = "system:serviceaccount:firemud-prod:firemud-app"; + assertThatThrownBy(() -> client(wrongPrincipal).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongPrincipal.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + FakeKubernetesApi wrongCluster = new FakeKubernetesApi(); + wrongCluster.kubeSystemUid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + assertThatThrownBy(() -> client(wrongCluster).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongCluster.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + FakeKubernetesApi wrongNamespace = new FakeKubernetesApi(); + wrongNamespace.targetNamespaceUid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + assertThatThrownBy(() -> client(wrongNamespace).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongNamespace.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE); + } + + @org.junit.jupiter.api.Test + void rejectsChangedProtectedTrustBeforeWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + ConfigMapSnapshot expected = client(api).observe(); + api.rejectPatchForChangedTrust = true; + + assertThatThrownBy(() -> client(api).publish(expected, desired("op-7"))) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)).isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void bearerRenewalIsAcceptedOnlyBeforeACompleteOperationAndModeOrOwnerDriftIsRejected() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + client.observe(); + api.bearerToken = "rotated-token"; + api.bearerFileKey = "rotated-inode"; + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + + api.calls.clear(); + api.bearerMode = "0444"; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + + api.bearerMode = "0440"; + api.bearerOwnerUid = 1001; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void bearerRotationMidVerificationCannotSplitSelfReviewFromConfigMapRead() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + api.rotateBearerAfterSelfReview = true; + + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + api.calls.clear(); + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + } + + @org.junit.jupiter.api.Test + void compareAndSetConflictNeverOverwritesChangedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + api.resourceVersion = "42"; + api.data.put("another-writer", "preserved"); + + assertThatThrownBy(() -> client.publish(expected, desired("op-8"))) + .isInstanceOf(CasConflictException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data).containsEntry("another-writer", "preserved"); + } + + @org.junit.jupiter.api.Test + void resourceReplacementAndApiConflictAreBothFenced() { + FakeKubernetesApi replacement = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient replacementClient = client(replacement); + ConfigMapSnapshot expected = replacementClient.observe(); + replacement.configMapUid = "44444444-4444-4444-8444-444444444444"; + + assertThatThrownBy(() -> replacementClient.publish(expected, desired("op-replaced"))) + .isInstanceOf(CasConflictException.class); + assertThat(replacement.patchCount).isZero(); + + FakeKubernetesApi inFlightConflict = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient inFlightClient = client(inFlightConflict); + ConfigMapSnapshot beforePatch = inFlightClient.observe(); + inFlightConflict.conflictNextPatch = true; + + assertThatThrownBy(() -> inFlightClient.publish(beforePatch, desired("op-conflict"))) + .isInstanceOf(CasConflictException.class); + assertThat(inFlightConflict.patchCount).isEqualTo(1); + assertThat(inFlightConflict.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)) + .isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void rejectsPrivateJwkMaterialBeforeAnyApiCall() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map privateJwks = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + "{\"keys\":[{\"kty\":\"RSA\",\"d\":\"private\"}]}", + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("op-private")); + + assertThatThrownBy( + () -> + client(api) + .publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account public JWKS contains private material"); + + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void lostPatchAcknowledgementSucceedsOnlyAfterExactSameUidContentReadback() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-9"); + api.loseNextPatchAcknowledgement = true; + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(result.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void exactDataAtTheUnchangedExpectedVersionIsNotReportedAsCasSuccess() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map desired = desired("already-present-operation"); + api.data.putAll(desired); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + + assertThatThrownBy(() -> client.publish(expected, desired)) + .isInstanceOf(CasConflictException.class) + .hasMessage("Account public JWKS ConfigMap compare-and-set conflict"); + + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo(expected.resourceVersion()); + } + + @org.junit.jupiter.api.Test + void updatePreservesUnrelatedDataAndPatchContainsOnlyOwnedPublicEntries() throws Exception { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-10"); + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.data) + .containsEntry("unrelated.txt", "retain") + .containsEntry(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, JWKS_NEW) + .containsEntry( + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, marker("durable-operation-10")); + JsonNode patch = JSON.readTree(api.lastPatch); + assertThat(patch.get("metadata").size()).isEqualTo(2); + assertThat(patch.get("metadata").get("uid").asText()).isEqualTo(CONFIG_MAP_UID); + assertThat(patch.get("metadata").get("resourceVersion").asText()).isEqualTo("41"); + assertThat(patch.get("data").size()).isEqualTo(2); + assertThat(patch.get("data").has("unrelated.txt")).isFalse(); + } + + @org.junit.jupiter.api.Test + void activeMarkerCasUsesFreshSnapshotAndPreservesUnrelatedEntries() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + + CasObservation result = client.publishActiveProjection(observed, "41", desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.readbackData()).containsEntry("unrelated.txt", "retain"); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void activeMarkerLostAcknowledgementReplayRequiresAdvancedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.loseNextPatchAcknowledgement = true; + + CasObservation applied = client.publishActiveProjection(observed, "41", desired); + + assertThat(applied.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(applied.priorResourceVersion()).isEqualTo("41"); + assertThat(applied.resourceVersion()).isEqualTo("42"); + int writes = api.patchCount; + CasObservation replay = client.publishActiveProjection(client.observe(), "41", desired); + + assertThat(replay.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(replay.priorResourceVersion()).isEqualTo("41"); + assertThat(replay.resourceVersion()).isEqualTo("42"); + assertThat(api.patchCount).isEqualTo(writes); + assertThat(api.data).containsEntry("unrelated.txt", "retain"); + } + + @org.junit.jupiter.api.Test + void activeMarkerDoesNotTreatExactDataAtUnchangedPriorVersionAsSuccessfulCas() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.data.putAll(desired); + ConfigMapSnapshot observed = client.observe(); + + assertThatThrownBy(() -> client.publishActiveProjection(observed, "41", desired)) + .isInstanceOf(CasConflictException.class); + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo("41"); + } + + @org.junit.jupiter.api.Test + void jwksConfigMapAccessHasNoSecretListCreateOrDeleteCapability() { + assertThat(ApiCall.values()) + .noneMatch( + call -> + call.name().contains("SECRET") + || call.name().contains("CREATE") + || call.name().contains("DELETE")); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("JWKS_CONFIG_MAP")) + .containsExactly(ApiCall.READ_JWKS_CONFIG_MAP, ApiCall.PATCH_JWKS_CONFIG_MAP); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("LIST")) + .containsExactly(ApiCall.LIST_VALIDATOR_PODS); + } + + private static AccountJwtJwksConfigMapClient client(FakeKubernetesApi api) { + return new AccountJwtJwksConfigMapClient(api::beginOperation); + } + + private static ParsedBinding parsedBinding() { + return new ParsedBinding( + "revision-1", + "prod", + "prod-cluster-1", + URI.create("https://kubernetes.example:6443/"), + "kubernetes.example", + java.nio.file.Path.of("/etc/firemud/kubernetes-ca.pem"), + "a".repeat(64), + java.nio.file.Path.of("/var/run/secrets/firemud/kubernetes/token"), + NAMESPACE, + KUBE_SYSTEM_UID, + TARGET_NAMESPACE_UID, + API_USERNAME, + "b".repeat(64)); + } + + private static Map desired(String operation) { + return Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_NEW, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker(operation)); + } + + private static String marker(String operation) { + return "{\"ownerOperation\":\"" + operation + "\"}"; + } + + private static String namespaceJson(String name, String uid) { + return "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"" + + name + + "\",\"uid\":\"" + + uid + + "\"},\"status\":{\"phase\":\"Active\"}}"; + } + + private static final class FakeKubernetesApi { + private final List calls = new ArrayList<>(); + private final Map data = + new LinkedHashMap<>( + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + "{\"ownerOperation\":\"old\"}", + "unrelated.txt", + "retain")); + private String authenticatedUsername = API_USERNAME; + private String kubeSystemUid = KUBE_SYSTEM_UID; + private String targetNamespaceUid = TARGET_NAMESPACE_UID; + private String configMapUid = CONFIG_MAP_UID; + private String resourceVersion = "41"; + private String bearerToken = "initial-token"; + private String bearerFileKey = "initial-inode"; + private long bearerOwnerUid; + private long bearerGroupId = 2000; + private String bearerMode = "0440"; + private boolean resourceExists = true; + private boolean oversizedConfigMapResponse; + private boolean rejectPatchForChangedTrust; + private boolean conflictNextPatch; + private boolean loseNextPatchAcknowledgement; + private boolean rotateBearerAfterSelfReview; + private int patchCount; + private String lastPatch; + private Long acceptedBearerOwnerUid; + private Long acceptedBearerGroupId; + private String acceptedBearerMode; + + private ApiSession beginOperation() { + if (acceptedBearerOwnerUid == null) { + acceptedBearerOwnerUid = bearerOwnerUid; + acceptedBearerGroupId = bearerGroupId; + acceptedBearerMode = bearerMode; + } + if (acceptedBearerOwnerUid != bearerOwnerUid + || acceptedBearerGroupId != bearerGroupId + || !acceptedBearerMode.equals(bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return new FakeApiSession(this, bearerToken, bearerFileKey); + } + + private ApiResponse send(ApiCall call, byte[] body) { + calls.add(call); + ApiResponse response = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + response( + 201, + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\"," + + "\"status\":{\"userInfo\":{\"username\":\"" + + authenticatedUsername + + "\"}}}"); + case READ_KUBE_SYSTEM_NAMESPACE -> + response(200, namespaceJson("kube-system", kubeSystemUid)); + case READ_TARGET_NAMESPACE -> + response(200, namespaceJson(NAMESPACE, targetNamespaceUid)); + case READ_JWKS_CONFIG_MAP -> + !resourceExists + ? response(404, "{}") + : oversizedConfigMapResponse + ? response(200, " ".repeat(1024 * 1024 + 1)) + : response(200, configMapJson()); + case PATCH_JWKS_CONFIG_MAP -> patch(body); + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new AssertionError("Unexpected validator call in ConfigMap client test"); + }; + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL && rotateBearerAfterSelfReview) { + rotateBearerAfterSelfReview = false; + bearerToken = "rotated-during-operation"; + bearerFileKey = "rotated-during-operation-inode"; + } + return response; + } + + private ApiResponse patch(byte[] body) { + if (rejectPatchForChangedTrust) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + patchCount++; + lastPatch = new String(body, StandardCharsets.UTF_8); + if (conflictNextPatch) { + conflictNextPatch = false; + return response(409, "{}"); + } + JsonNode patch; + try { + patch = JSON.readTree(lastPatch); + } catch (Exception ex) { + throw new AssertionError(ex); + } + JsonNode metadata = patch.get("metadata"); + if (!CONFIG_MAP_UID.equals(metadata.get("uid").asText()) + || !resourceVersion.equals(metadata.get("resourceVersion").asText())) { + return response(409, "{}"); + } + JsonNode patchData = patch.get("data"); + patchData.properties().forEach(entry -> data.put(entry.getKey(), entry.getValue().asText())); + resourceVersion = Long.toString(Long.parseLong(resourceVersion) + 1); + if (loseNextPatchAcknowledgement) { + loseNextPatchAcknowledgement = false; + throw new AccountJwtJwksApiBinding.ApiTransportException(); + } + return response(200, configMapJson()); + } + + private String configMapJson() { + try { + Map metadata = + Map.of( + "name", AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", NAMESPACE, + "uid", configMapUid, + "resourceVersion", resourceVersion); + Map object = + Map.of("apiVersion", "v1", "kind", "ConfigMap", "metadata", metadata, "data", data); + return JSON.writeValueAsString(object); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static ApiResponse response(int status, String body) { + return new ApiResponse(status, body.getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class FakeApiSession implements ApiSession { + private final FakeKubernetesApi api; + private final ParsedBinding binding = parsedBinding(); + private String bearerTokenSnapshot; + private String bearerFileKeySnapshot; + + private FakeApiSession(FakeKubernetesApi api, String token, String fileKey) { + this.api = api; + this.bearerTokenSnapshot = token; + this.bearerFileKeySnapshot = fileKey; + } + + @Override + public ParsedBinding binding() { + return binding; + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + if (bearerTokenSnapshot == null + || !bearerTokenSnapshot.equals(api.bearerToken) + || !bearerFileKeySnapshot.equals(api.bearerFileKey) + || api.acceptedBearerOwnerUid != api.bearerOwnerUid + || api.acceptedBearerGroupId != api.bearerGroupId + || !api.acceptedBearerMode.equals(api.bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return api.send(call, body); + } + + @Override + public void close() { + bearerTokenSnapshot = null; + bearerFileKeySnapshot = null; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java new file mode 100644 index 0000000000..ab0d7af8f8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -0,0 +1,677 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJwtJwksTrustedSourceTest { + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_BINDING_DIGEST = "a".repeat(64); + private static final String API_CA_DIGEST = "b".repeat(64); + private static final UUID INITIAL_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000001"); + private static final UUID NEXT_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000002"); + private static final String GENERATION_OPERATION_DIGEST = "1".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "2".repeat(64); + private static final String GENERATION_RECEIPT_DIGEST = "3".repeat(64); + private static final String JWK_1 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_1\",\"kty\":\"RSA\",\"n\":\"AQID\",\"use\":\"sig\"}"; + private static final String JWK_2 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_2\",\"kty\":\"RSA\",\"n\":\"BAUG\",\"use\":\"sig\"}"; + private static final String JWKS_1 = "{\"keys\":[" + JWK_1 + "]}"; + private static final String JWKS_1_AND_2 = "{\"keys\":[" + JWK_1 + "," + JWK_2 + "]}"; + + @Test + void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { + Fixture fixture = new Fixture(); + + SourceIdentity identity = fixture.source.sourceIdentity(); + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(identity.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(identity.clusterId()).isEqualTo(CLUSTER); + assertThat(identity.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(identity.namespace()).isEqualTo(NAMESPACE); + assertThat(identity.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(identity.bindingRevision()).isEqualTo("api-r1"); + assertThat(identity.apiServerOrigin()).isEqualTo("https://kubernetes.test:6443"); + assertThat(identity.servingCaSha256()).isEqualTo(API_CA_DIGEST); + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()) + .containsExactly(fixture.publicJwks.getBytes(StandardCharsets.UTF_8)); + verify(fixture.desiredStateRepository, never()) + .readCurrentCommittedSigner(any(), any(), any(), any()); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + + @Test + void allowsNewAccountPublicationAtSamePinnedResourceWithoutChangingSourceIdentity() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + SourceIdentity identity = fixture.source.sourceIdentity(); + String nextJwks = JWKS_1_AND_2; + String nextMarker = + fixture.marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + fixture.publication( + nextJwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + Map nextData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + nextJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(nextPublication), Optional.of(nextPublication)); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", nextData)); + + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(nextJwks.getBytes(StandardCharsets.UTF_8)); + assertThat(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)).contains(JWK_1, JWK_2); + } + + @Test + void historicalKeyFingerprintRequiresTheCurrentOwnerProvedSetToRetainItsExactIdentity() { + Fixture missingKey = new Fixture(); + missingKey.useCommittedState(); + missingKey.replaceNextJwks("{\"keys\":[" + JWK_2 + "]}"); + assertThatThrownBy(missingKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + + Fixture substitutedKey = new Fixture(); + substitutedKey.useCommittedState(); + String substitutedJwk = JWK_1.replace("\"n\":\"AQID\"", "\"n\":\"BAUG\""); + substitutedKey.replaceNextJwks("{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"); + assertThatThrownBy(substitutedKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void deniesSameNamedDestinationWithDifferentClusterIncarnation() { + Fixture fixture = new Fixture(); + Binding wrongIncarnation = binding("44444444-4444-4444-8444-444444444444", NAMESPACE_UID); + when(fixture.materializerTrust.current()).thenReturn(Optional.of(wrongIncarnation)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesUnexpectedAuthenticatedApiPrincipal() { + Fixture fixture = new Fixture(); + BindingIdentity wrongPrincipal = + new BindingIdentity( + fixture.apiIdentity.bindingDigest(), + fixture.apiIdentity.configRevision(), + fixture.apiIdentity.environmentId(), + fixture.apiIdentity.clusterId(), + fixture.apiIdentity.namespace(), + fixture.apiIdentity.expectedClusterIncarnationUid(), + fixture.apiIdentity.expectedNamespaceUid(), + fixture.apiIdentity.apiServerUrl(), + fixture.apiIdentity.tlsServerName(), + fixture.apiIdentity.servingCaSha256(), + "system:serviceaccount:" + NAMESPACE + ":another-service"); + when(fixture.configMapClient.identity()).thenReturn(wrongPrincipal); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.publicationRepository, never()).readCurrentPublication(any(), any()); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsRecreatedSameNameConfigMapEvenWithMatchingPublicData() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { + Fixture fixture = new Fixture(); + PublicationEvidence unreceipted = + new PublicationEvidence(fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(unreceipted)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsTrustChangeAcrossTheAuthenticatedRead() { + Fixture fixture = new Fixture(); + Binding changedBinding = binding(CLUSTER_UID, NAMESPACE_UID, "materializer-r2"); + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(fixture.binding), Optional.of(changedBinding)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void rejectsReadbackThatDoesNotMatchReceiptResourceVersionOrMarker() { + Fixture fixture = new Fixture(); + Map changedData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + fixture.publicJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + "{\"phase\":\"OTHER\"}"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedData)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void ownerPublicationChangingDuringReadProducesNoSnapshot() { + Fixture fixture = new Fixture(); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(fixture.publication), Optional.empty()); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + + @Test + void deniesInitialPrepublicationWhenPublicMarkerClaimsAnActiveFence() { + Fixture fixture = new Fixture(); + String activeMarker = + fixture.marker( + INITIAL_OPERATION_ID, + "1", + "key_1", + fingerprint(JWK_1), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence conflicting = + fixture.publication( + fixture.publicJwks, activeMarker, "41", "42", "1", "key_1", Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(conflicting)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesInitialPrepublicationWhenConfigMapResourceVersionIsStale() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + private static Binding binding(String clusterUid, String namespaceUid) { + return binding(clusterUid, namespaceUid, "materializer-r1"); + } + + private static Binding binding(String clusterUid, String namespaceUid, String revision) { + String expectedPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/jwt-signer-materializer"; + List pins = List.of("c".repeat(64)); + String bindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins); + return new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + bindingDigest); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } + + private static final class Fixture { + private final AccountJwtJwksConfigMapClient configMapClient = + mock(AccountJwtJwksConfigMapClient.class); + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final Binding binding = binding(CLUSTER_UID, NAMESPACE_UID); + private final TrustFence trustFence = + new TrustFence( + CLUSTER_UID, NAMESPACE_UID, binding.bindingDigest(), binding.configRevision()); + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding = + binding.accountBinding(); + private final BindingIdentity apiIdentity = + new BindingIdentity( + API_BINDING_DIGEST, + "api-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.test:6443", + "kubernetes.test", + API_CA_DIGEST, + "system:serviceaccount:" + NAMESPACE + ":account-service"); + private final String publicFingerprint = fingerprint(JWK_1); + private final String publicJwks = JWKS_1; + private final EnrollmentIdentity enrollmentIdentity; + private final GenerationRequest initialRequest; + private final GenerationResult initialResult; + private final DesiredState initialDesiredState; + private final String initialMarker; + private final PublicationEvidence publication; + private final ConfigMapSnapshot snapshot; + private final AccountJwtJwksTrustedSource source; + + private Fixture() { + enrollmentIdentity = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + binding.bindingDigest(), + binding.configRevision(), + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "40", + "6".repeat(64)); + initialMarker = + marker(INITIAL_OPERATION_ID, "1", "key_1", publicFingerprint, Optional.empty()); + initialRequest = mock(GenerationRequest.class); + when(initialRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(initialRequest.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(initialRequest.desiredStateVersion()).thenReturn(2L); + when(initialRequest.binding()).thenReturn(accountBinding); + when(initialRequest.trustFence()).thenReturn(trustFence); + when(initialRequest.targetGeneration()).thenReturn("1"); + when(initialRequest.targetKid()).thenReturn("key_1"); + when(initialRequest.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialRequest.publicJwkJson()).thenReturn(JWK_1); + when(initialRequest.expectedActive()).thenReturn(Optional.empty()); + when(initialRequest.expectedPublishedActive()).thenReturn(Optional.empty()); + + initialResult = mock(GenerationResult.class); + when(initialResult.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialResult.binding()).thenReturn(accountBinding); + when(initialResult.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialResult.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialResult.desiredStateVersion()).thenReturn(2L); + when(initialResult.trustFence()).thenReturn(trustFence); + when(initialResult.targetGeneration()).thenReturn("1"); + when(initialResult.targetKid()).thenReturn("key_1"); + when(initialResult.targetAlgorithm()).thenReturn("RS256"); + when(initialResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialResult.publicJwkJson()).thenReturn(JWK_1); + when(initialResult.receiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + + initialDesiredState = + new DesiredState( + accountBinding, + 2, + Optional.empty(), + Optional.empty(), + Optional.of(INITIAL_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + publication = + publication(publicJwks, initialMarker, "41", "42", "1", "key_1", Optional.empty()); + snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + publicJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + initialMarker, + "operator.note", + "retained")); + + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(materializerTrust.current()).thenReturn(Optional.of(binding)); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()).thenReturn(snapshot); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(initialDesiredState)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(initialRequest); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(initialResult); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(publication)); + source = + new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrust, + desiredStateRepository, + publicationRepository, + transactionManager); + } + + private void useCommittedState() { + ActiveSigner active = new ActiveSigner("1", "key_1"); + DesiredState committedState = + new DesiredState( + accountBinding, + 3, + Optional.of(active), + Optional.of(active), + Optional.of(NEXT_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt receipt = + mock(AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt.class); + String activeMarker = activeMarker(active); + String activeDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(publicJwks, activeMarker); + when(committed.promotion()).thenReturn(promotion); + when(committed.desiredState()).thenReturn(committedState); + when(committed.publicReceipt()).thenReturn(receipt); + when(promotion.targetGeneration()).thenReturn("1"); + when(promotion.targetKid()).thenReturn("key_1"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicJwksJson()).thenReturn(publicJwks); + when(promotion.expectedActiveMarkerJson()).thenReturn(activeMarker); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("42")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(activeDigest)); + when(receipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.publicDataDigest()).thenReturn(activeDigest); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(committedState)); + when(desiredStateRepository.readCurrentCommittedSigner( + eq(accountBinding), eq(trustFence), eq(API_BINDING_DIGEST), eq("api-r1"))) + .thenReturn(Optional.of(committed)); + + GenerationRequest nextRequest = mock(GenerationRequest.class); + when(nextRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(nextRequest.operationId()).thenReturn(NEXT_OPERATION_ID); + when(nextRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(nextRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(nextRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(nextRequest.desiredStateVersion()).thenReturn(2L); + when(nextRequest.targetGeneration()).thenReturn("2"); + when(nextRequest.targetKid()).thenReturn("key_2"); + when(nextRequest.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); + when(nextRequest.expectedActive()).thenReturn(Optional.of(active)); + when(nextRequest.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(nextRequest); + + String nextMarker = + marker(NEXT_OPERATION_ID, "2", "key_2", fingerprint(JWK_2), Optional.of(active)); + PublicationEvidence nextPublication = + publication(JWKS_1_AND_2, nextMarker, "42", "43", "2", "key_2", Optional.of(active)); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private void replaceNextJwks(String jwks) { + String nextMarker = + marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + publication( + jwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private PublicationEvidence publication( + String jwks, + String marker, + String expectedResourceVersion, + String observedResourceVersion, + String generation, + String kid, + Optional expectedActive) { + String publicDataDigest = AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker); + String keyFingerprint = "key_1".equals(kid) ? fingerprint(JWK_1) : fingerprint(JWK_2); + UUID operationId = "1".equals(generation) ? INITIAL_OPERATION_ID : NEXT_OPERATION_ID; + PrepublicationIntent intent = + PrepublicationIntent.create( + operationId, + accountBinding, + GENERATION_OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + GENERATION_RECEIPT_DIGEST, + 2L, + trustFence, + API_BINDING_DIGEST, + "api-r1", + AccountJwtJwksPublicationRepository.PUBLIC_JWKS_NAME, + CONFIG_MAP_UID, + expectedResourceVersion, + "4".repeat(64), + generation, + kid, + keyFingerprint, + expectedActive, + expectedActive, + jwks, + marker, + publicDataDigest, + sha256(marker)); + PublicationReceipt receipt = PublicationReceipt.create(intent, observedResourceVersion); + return new PublicationEvidence(intent, Optional.of(receipt), Optional.empty()); + } + + private String marker( + UUID operationId, + String generation, + String kid, + String keyFingerprint, + Optional active) { + String activeJson = activeMarker(active); + return "{\"schemaVersion\":1,\"phase\":\"PREPUBLISHED\",\"operationId\":\"" + + operationId + + "\",\"operationDigest\":\"" + + GENERATION_OPERATION_DIGEST + + "\",\"generationRequestDigest\":\"" + + GENERATION_REQUEST_DIGEST + + "\",\"generationReceiptDigest\":\"" + + GENERATION_RECEIPT_DIGEST + + "\",\"binding\":{\"environmentId\":\"" + + ENVIRONMENT + + "\",\"clusterId\":\"" + + CLUSTER + + "\",\"namespace\":\"" + + NAMESPACE + + "\",\"expectedClusterIncarnationUid\":\"" + + CLUSTER_UID + + "\",\"expectedNamespaceUid\":\"" + + NAMESPACE_UID + + "\",\"trustBindingDigest\":\"" + + binding.bindingDigest() + + "\",\"trustConfigRevision\":\"" + + binding.configRevision() + + "\",\"apiBindingDigest\":\"" + + API_BINDING_DIGEST + + "\",\"apiConfigRevision\":\"api-r1\"},\"publicConfigMap\":{\"name\":\"jwt-jwks\"},\"expectedDurableActive\":" + + activeJson + + ",\"expectedPublishedActive\":" + + activeJson + + ",\"pending\":{\"generation\":\"" + + generation + + "\",\"kid\":\"" + + kid + + "\",\"algorithm\":\"RS256\",\"publicKeyFingerprint\":\"" + + keyFingerprint + + "\"}}"; + } + } + + private static String activeMarker(ActiveSigner active) { + return "{\"generation\":\"" + + active.generation() + + "\",\"kid\":\"" + + active.kid() + + "\",\"present\":true}"; + } + + private static String activeMarker(Optional active) { + return active.map(AccountJwtJwksTrustedSourceTest::activeMarker).orElse("{\"present\":false}"); + } + + private static String fingerprint(String jwk) { + String modulus = jwk.contains("key_1") ? "AQID" : "BAUG"; + String preimage = "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"" + modulus + "\"}"; + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(Rfc8785CanonicalJson.canonicalizeUtf8(preimage))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..aec108b44d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable shared value and canonical codec for ADR 0048's StartSession {@code + * preAuthorizationReservationTuple/v1}. + * + *

This value describes tuple contents only. Constructing or rehydrating it does not establish + * authenticated actor authority, reservation ownership, a claim, or permission to dispatch. + */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = "preAuthorizationReservationTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = 128; + private static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason"); + + private final String controlPlaneRequestId; + private final HumanActor actor; + private final StartSessionOperatorAction action; + + private StartSessionPreAuthorizationReservationTuple( + String controlPlaneRequestId, HumanActor actor, StartSessionOperatorAction action) { + this.controlPlaneRequestId = requireCanonicalControlPlaneRequestId(controlPlaneRequestId); + this.actor = Objects.requireNonNull(actor, "actor is required"); + this.action = Objects.requireNonNull(action, "action is required"); + } + + /** Creates tuple contents from typed values; the actor argument is not authenticated evidence. */ + public static StartSessionPreAuthorizationReservationTuple createHuman( + String controlPlaneRequestId, UUID actorAccountId, StartSessionOperatorAction action) { + return new StartSessionPreAuthorizationReservationTuple( + controlPlaneRequestId, new HumanActor(actorAccountId), action); + } + + /** Rehydrates the exact canonical ADR 0048 tuple value. This does not establish authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + Objects.requireNonNull(json, "tuple JSON is required"); + if (json.getBytes(StandardCharsets.UTF_8).length > MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("pre-authorization tuple exceeds its byte limit"); + } + try { + String canonical = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonical.equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple is not canonical JSON"); + } + Object decoded = JSON.readValue(json, Map.class); + Map root = requireObject(decoded, "tuple"); + requireExactFields(root, ROOT_FIELDS, "tuple"); + if (!TUPLE_SCHEMA_ID.equals(requireString(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + requireString(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw new IllegalArgumentException("unsupported pre-authorization tuple schema"); + } + + Map identity = + requireObject(root.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireExactFields( + identity, Set.of("requestIdentityKind", "requestId"), "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId" + .equals(requireString(identity.get("requestIdentityKind"), "requestIdentityKind"))) { + throw new IllegalArgumentException( + "StartSession request identity must be controlPlaneRequestId"); + } + String controlPlaneRequestId = requireString(identity.get("requestId"), "requestId"); + + Map actorObject = requireObject(root.get("actor"), "actor"); + requireExactFields(actorObject, Set.of("kind", "accountId"), "actor"); + if (!"HUMAN".equals(requireString(actorObject.get("kind"), "actor.kind"))) { + throw new IllegalArgumentException("StartSession reservation actor must be human"); + } + HumanActor actor = + new HumanActor(requireCanonicalUuid(actorObject.get("accountId"), "actor.accountId")); + + Map automation = + requireObject(root.get("automationPolicy"), "automationPolicy"); + requireExactFields(automation, Set.of("presence"), "automationPolicy"); + if (!"ABSENT" + .equals(requireString(automation.get("presence"), "automationPolicy.presence"))) { + throw new IllegalArgumentException( + "human StartSession tuple must explicitly omit automation policy"); + } + + String actionFamily = requireString(root.get("actionFamily"), "actionFamily"); + String schemaId = requireString(root.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requireString(root.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(actionFamily) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw new IllegalArgumentException("unsupported StartSession action-family schema"); + } + + Map scopeObject = requireObject(root.get("scope"), "scope"); + requireExactFields(scopeObject, Set.of("tenantId", "targetNamespace"), "scope"); + StartSessionOperatorAction.Scope scope = + new StartSessionOperatorAction.Scope( + requireCanonicalUuid(scopeObject.get("tenantId"), "scope.tenantId"), + requireString(scopeObject.get("targetNamespace"), "scope.targetNamespace")); + + Map targetObject = requireObject(root.get("target"), "target"); + requireExactFields(targetObject, Set.of("gameTemplateId", "ownerAccountId"), "target"); + StartSessionOperatorAction.Target target = + new StartSessionOperatorAction.Target( + requirePositiveCanonicalLong(targetObject.get("gameTemplateId")), + requireCanonicalUuid(targetObject.get("ownerAccountId"), "target.ownerAccountId")); + + Map ownerObject = requireObject(root.get("targetOwner"), "targetOwner"); + requireExactFields(ownerObject, Set.of("ownerService"), "targetOwner"); + if (!StartSessionOperatorAction.OWNER_SERVICE.equals( + requireString(ownerObject.get("ownerService"), "targetOwner.ownerService"))) { + throw new IllegalArgumentException("StartSession targetOwner is immutable and unsupported"); + } + + Map expectedVersion = + requireObject(root.get("expectedVersion"), "expectedVersion"); + requireExactFields(expectedVersion, Set.of("presence"), "expectedVersion"); + if (!"ABSENT" + .equals(requireString(expectedVersion.get("presence"), "expectedVersion.presence"))) { + throw new IllegalArgumentException( + "StartSession expectedVersion must be explicitly absent"); + } + + Map mutationObject = requireObject(root.get("mutation"), "mutation"); + requireExactFields(mutationObject, Set.of("clientIp"), "mutation"); + Map clientIpObject = + requireObject(mutationObject.get("clientIp"), "mutation.clientIp"); + String clientIpPresence = + requireString(clientIpObject.get("presence"), "mutation.clientIp.presence"); + StartSessionOperatorAction.ClientIp clientIp; + if ("ABSENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence"), "mutation.clientIp"); + clientIp = StartSessionOperatorAction.ClientIp.absent(); + } else if ("PRESENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence", "value"), "mutation.clientIp"); + clientIp = + StartSessionOperatorAction.ClientIp.of( + requireString(clientIpObject.get("value"), "mutation.clientIp.value")); + } else { + throw new IllegalArgumentException("mutation.clientIp presence must be ABSENT or PRESENT"); + } + + StartSessionOperatorAction action = + new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + requireString(root.get("auditReason"), "auditReason")); + StartSessionPreAuthorizationReservationTuple tuple = + new StartSessionPreAuthorizationReservationTuple(controlPlaneRequestId, actor, action); + if (!tuple.canonicalJson().equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple shape is not canonical"); + } + return tuple; + } catch (IOException exception) { + throw new IllegalArgumentException("pre-authorization tuple JSON is invalid", exception); + } + } + + public String actionFamily() { + return action.actionFamily(); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public HumanActor actor() { + return actor; + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return action; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId is required"); + if (!Normalizer.isNormalized(value, Normalizer.Form.NFC)) { + throw new IllegalArgumentException("controlPlaneRequestId must already be NFC-normalized"); + } + return requireBoundedText(value, "controlPlaneRequestId"); + } + + public String targetOwner() { + return action.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return StartSessionOperatorActionCodec.mutationDigest(action); + } + + /** Returns the complete canonical typed tuple, including explicit absence values. */ + public String canonicalJson() { + Map scope = + Map.of( + "tenantId", action.scope().tenantId().toString(), + "targetNamespace", action.scope().targetNamespace()); + Map target = + Map.of( + "gameTemplateId", Long.toString(action.target().gameTemplateId()), + "ownerAccountId", action.target().ownerAccountId().toString()); + Map clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? Map.of("presence", "ABSENT") + : Map.of( + "presence", + "PRESENT", + "value", + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put( + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", controlPlaneRequestId)); + root.put("actor", Map.of("kind", "HUMAN", "accountId", actor.accountId().toString())); + root.put("automationPolicy", Map.of("presence", automationPolicy().name())); + root.put("actionFamily", action.actionFamily()); + root.put("actionFamilySchemaId", action.actionFamilySchemaId()); + root.put("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + root.put("scope", scope); + root.put("target", target); + root.put("targetOwner", Map.of("ownerService", action.targetOwner())); + root.put("expectedVersion", Map.of("presence", action.expectedVersion().name())); + root.put("mutation", Map.of("clientIp", clientIp)); + root.put("auditReason", action.auditReason()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException("could not encode StartSession reservation tuple", exception); + } + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StartSessionPreAuthorizationReservationTuple that)) { + return false; + } + return controlPlaneRequestId.equals(that.controlPlaneRequestId) + && actor.equals(that.actor) + && action.equals(that.action); + } + + @Override + public int hashCode() { + return Objects.hash(controlPlaneRequestId, actor, action); + } + + private static String requireBoundedText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + if (normalized.isBlank() + || normalized.codePoints().anyMatch(Character::isISOControl) + || normalized.getBytes(StandardCharsets.UTF_8).length + > MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES) { + throw new IllegalArgumentException(fieldName + " is blank or exceeds its bound"); + } + for (int index = 0; index < normalized.length(); index++) { + char current = normalized.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= normalized.length() + || !Character.isLowSurrogate(normalized.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + return normalized; + } + + private static UUID requireCanonicalUuid(Object value, String fieldName) { + String text = requireString(value, fieldName); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static long requirePositiveCanonicalLong(Object value) { + String text = requireString(value, "target.gameTemplateId"); + if (!text.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "target.gameTemplateId must be a positive canonical integer"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "target.gameTemplateId exceeds its supported range", exception); + } + } + + private static String requireString(Object value, String fieldName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException(fieldName + " must be a string"); + } + return text; + } + + @SuppressWarnings("unchecked") + private static Map requireObject(Object value, String fieldName) { + if (!(value instanceof Map map)) { + throw new IllegalArgumentException(fieldName + " must be an object"); + } + for (Object key : map.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException(fieldName + " contains a non-string field name"); + } + } + return (Map) map; + } + + private static void requireExactFields( + Map object, Set expectedFields, String fieldName) { + if (!object.keySet().equals(expectedFields)) { + throw new IllegalArgumentException(fieldName + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..3f881b6d5e --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OTHER_ACTOR_ID = + UUID.fromString("a44b728e-b58f-4fc1-a891-7644baef6ddc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + + @Test + void canonicalBytesMatchThePreAuthorizationReservationTupleV1Encoding() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-contract-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String expected = + "{\"actionFamily\":\"StartSession\"," + + "\"actionFamilyRequestIdentity\":{\"requestId\":\"tuple-contract-01\"," + + "\"requestIdentityKind\":\"controlPlaneRequestId\"}," + + "\"actionFamilySchemaId\":\"firemud.game-session.start-session\"," + + "\"actionFamilySchemaVersion\":\"1\"," + + "\"actor\":{\"accountId\":\"a4f5f4eb-8243-4d42-903a-33495456a622\"," + + "\"kind\":\"HUMAN\"}," + + "\"auditReason\":\"tuple codec contract\"," + + "\"automationPolicy\":{\"presence\":\"ABSENT\"}," + + "\"expectedVersion\":{\"presence\":\"ABSENT\"}," + + "\"mutation\":{\"clientIp\":{\"presence\":\"ABSENT\"}}," + + "\"scope\":{\"targetNamespace\":\"world-runtime\"," + + "\"tenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"}," + + "\"target\":{\"gameTemplateId\":\"91\"," + + "\"ownerAccountId\":\"36aa9ce5-0ebc-4c14-9f6b-d160edc6059a\"}," + + "\"targetOwner\":{\"ownerService\":\"game-session-service\"}," + + "\"tupleSchemaId\":\"preAuthorizationReservationTuple\"," + + "\"tupleSchemaVersion\":\"1\"}"; + + assertThat(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(expected) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(tuple.action())); + } + + @Test + void roundTripsTypedContentsAndSameRequestIdWithDifferentActorIsAConflict() { + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + StartSessionPreAuthorizationReservationTuple original = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", ACTOR_ID, action); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(original.canonicalJson()); + StartSessionPreAuthorizationReservationTuple changedActor = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", OTHER_ACTOR_ID, action); + + assertThat(rehydrated).isEqualTo(original); + assertThat(rehydrated.canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(rehydrated.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(changedActor.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(changedActor).isNotEqualTo(original); + assertThat(changedActor.canonicalJson()).isNotEqualTo(original.canonicalJson()); + // The action digest excludes reservation identity and actor; it cannot replace tuple + // comparison. + assertThat(changedActor.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(original.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + } + + @Test + void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-strict-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String json = tuple.canonicalJson(); + String withUnknownRootField = + json.replace( + "\"tupleSchemaVersion\":\"1\"}", "\"tupleSchemaVersion\":\"1\",\"unexpected\":true}"); + String missingTargetOwner = + json.replace(",\"targetOwner\":{\"ownerService\":\"game-session-service\"}", ""); + String invalidExpectedVersion = + json.replace( + "\"expectedVersion\":{\"presence\":\"ABSENT\"}", + "\"expectedVersion\":{\"presence\":\"PRESENT\"}"); + String invalidActorKind = json.replace("\"kind\":\"HUMAN\"", "\"kind\":\"WORKLOAD\""); + + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JSON"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + withUnknownRootField)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + invalidExpectedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedVersion"); + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidActorKind)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor must be human"); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "tuple codec contract"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java new file mode 100644 index 0000000000..6fdfb4fc5e --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.security; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Validates the canonical claim shape of the registry-backed control-ui JWT profile. */ +public final class ControlUiJwtProfileValidator { + public static final String PROFILE = "control-ui"; + public static final String AUDIENCE = "control-ui"; + public static final String TOKEN_TYPE = "control-ui"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private ControlUiJwtProfileValidator() {} + + /** + * Checks claim shape only; it does not validate a registry record or current Account authority. + * + * @param claims immutable verified claims + * @param maxControlUiTenantScopes explicit finite profile cap for every applicable tenant map + */ + public static void validateClaims(Map claims, int maxControlUiTenantScopes) { + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw AccountJwtProfileClaimSupport.invalid(); + } + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + + Map tuple = + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), true, false, false); + if (!(tuple.get("privateRealmGrantVersions") instanceof List grants) || !grants.isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + Map tenantGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap(tuple.get("tenantAuthorityGeneration")); + Map membershipGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap( + tuple.get("membershipAuthorityGeneration")); + Map membershipVersions = + AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")); + String accountId = (String) claims.get("accountId"); + // The canonical profile forbids an accountId as a tenant-map key; this is shape rejection, + // not evidence about tenant ownership or an authorization predicate. + if (!membershipGenerations.keySet().equals(membershipVersions.keySet()) + || tenantGenerations.containsKey(accountId) + || membershipGenerations.containsKey(accountId) + || membershipVersions.containsKey(accountId)) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + Map scopedRoles = + AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")); + scopedRoles.forEach( + (tenantId, roles) -> { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireRoleList(roles); + if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + }); + if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + requireAtMost(scopedRoles.size(), maxControlUiTenantScopes); + requireAtMost(tenantGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipVersions.size(), maxControlUiTenantScopes); + + Object billingCutoff = tuple.get("tenantBillingCutoff"); + if (billingCutoff != null) { + Map billingCutoffs = + AccountJwtProfileClaimSupport.requireObjectMap(billingCutoff); + requireAtMost(billingCutoffs.size(), maxControlUiTenantScopes); + if (!scopedRoles.keySet().containsAll(billingCutoffs.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } + + private static void requireAtMost(int entries, int maximum) { + if (entries > maximum) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } +} + diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java new file mode 100644 index 0000000000..d75869b238 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -0,0 +1,891 @@ +package net.firedevops.firemud.common.security; + +import java.io.IOException; +import java.nio.ByteBuffer; +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.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Strict finite-bounded codec for initial and distinct public-production bound delegation + * candidates. + * + *

Pending records are non-authorizing. This codec checks JOSE/claim shape and exact Account + * snapshot equality, but does not verify the JWS signature or establish signer/currentness proof. + * The signing and Account evidence owners must do that before any active transition is usable. + */ +public final class GameSessionAccountDelegationRegistryRecord { + private static final int SCHEMA_VERSION = 2; + private static final int PENDING_REGISTRY_VERSION = 1; + private static final int ACTIVE_REGISTRY_VERSION = 2; + private static final String PENDING = "pending"; + private static final String ACTIVE = "active"; + private static final Pattern HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_LINEARIZATION = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Set TOKEN_CLAIMS = + Set.of( + "iss", + "sub", + "jti", + "accountId", + "aud", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence"); + private static final Set HEADER_REQUIRED = Set.of("alg", "kid"); + private static final Set HEADER_ALLOWED = Set.of("alg", "kid", "typ"); + private static final Set RECORD_FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "accountId", + "issuer", + "profile", + "type", + "audience", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "operationId", + "requestId", + "requestDigest", + "state", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "authEvidenceBundle"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + + private GameSessionAccountDelegationRegistryRecord(Map fields) { + this.fields = immutableMap(fields); + } + + /** Creates the distinct first public-production tenant-bound pending record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedBoundCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot account, + EvidenceBundleReference evidence, + String tenantId, + Map exactTuple, + Map exactMembershipVersion, + long now, + long maxBytes) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenantId, exactTuple, exactMembershipVersion); + return fromCandidate( + compactJwt, + signerGeneration, + binding, + account, + evidence, + now, + maxBytes, + new BoundShape(tenantId, exactTuple, exactMembershipVersion)); + } + + private record BoundShape( + String tenantId, Map tuple, Map membershipVersion) {} + + /** Validates the exact signed-token candidate and creates only its pending registry record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes) { + return fromCandidate( + compactJwt, + signerGeneration, + binding, + snapshot, + evidenceBundleReference, + nowEpochSecond, + maxRecordBytes, + null); + } + + private static GameSessionAccountDelegationRegistryRecord fromCandidate( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes, + BoundShape bound) { + Objects.requireNonNull(compactJwt, "Compact Account JWT is required"); + Objects.requireNonNull(binding, "Durable issuance binding is required"); + Objects.requireNonNull(snapshot, "Locked Account authority snapshot is required"); + Objects.requireNonNull( + evidenceBundleReference, "Persisted Account evidence bundle is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + requirePositive(nowEpochSecond, "nowEpochSecond"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + + CompactToken compact = parseCompactJwt(compactJwt); + Map claims = compact.claims(); + requireExactFields(claims, fieldsFor(TOKEN_CLAIMS, bound != null), "JWT claims"); + String issuer = requireText(claims.get("iss"), "iss", 256); + String subject = requireCanonicalUuid(claims.get("sub"), "sub"); + String accountId = requireCanonicalUuid(claims.get("accountId"), "accountId"); + String jti = requireCanonicalUuid(claims.get("jti"), "jti"); + String audience = requireText(claims.get("aud"), "aud", 128); + long issuedAt = requirePositiveInteger(claims.get("iat"), "iat"); + long notBefore = requirePositiveInteger(claims.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(claims.get("exp"), "exp"); + String tokenGeneration = + requirePositiveDecimal(claims.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = requirePositiveDecimal(claims.get("issuanceFence"), "issuanceFence"); + + requireEqual(GameSessionAccountDelegationProfile.ISSUER, issuer, "Account issuer mismatch"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, audience, "audience mismatch"); + requireEqual(snapshot.accountId().toString(), accountId, "Account UUID mismatch"); + requireEqual(subject, accountId, "sub and accountId mismatch"); + requireEqual(binding.accountId(), accountId, "durable operation account mismatch"); + requireEqual("1", tokenGeneration, "initial delegation tokenGeneration must be one"); + requireEqual( + Long.toString(snapshot.issuanceFence()), issuanceFence, "Account issuance fence mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, nowEpochSecond); + if (bound == null) { + validateAuthorityTuple( + claims.get("authorityTuple"), claims.get("membershipVersion"), snapshot); + } else { + GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(claims); + requireEqual(bound.tenantId(), claims.get("tenantId"), "bound tenant mismatch"); + requireEqual(bound.tuple(), claims.get("authorityTuple"), "bound tuple mismatch"); + requireEqual( + bound.membershipVersion(), + claims.get("membershipVersion"), + "independent membership version mismatch"); + requireEqual( + Long.toString(snapshot.issuerGeneration()), + bound.tuple().get("issuerAuthGeneration"), + "issuer mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + bound.tuple().get("accountAuthorityGeneration"), + "account mismatch"); + if (!Objects.equals( + snapshot.accountSecurityCutoff().map(value -> value.toMap()).orElse(null), + bound.tuple().get("accountSecurityCutoff"))) throw invalid("Account cutoff mismatch"); + } + + Map record = new LinkedHashMap<>(); + record.put("schemaVersion", SCHEMA_VERSION); + record.put("registryVersion", PENDING_REGISTRY_VERSION); + record.put("tokenHash", sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))); + record.put("kid", compact.keyId()); + record.put("signerGeneration", signerGeneration); + record.put("accountId", accountId); + if (bound != null) record.put("tenantId", bound.tenantId()); + record.put("issuer", issuer); + record.put("profile", GameSessionAccountDelegationProfile.PROFILE); + record.put("type", GameSessionAccountDelegationProfile.TYPE); + record.put("audience", audience); + record.put("jti", jti); + record.put("iat", issuedAt); + record.put("nbf", notBefore); + record.put("exp", expiresAt); + record.put("tokenGeneration", tokenGeneration); + record.put("operationId", binding.operationId()); + record.put("requestId", binding.requestId()); + record.put("requestDigest", binding.requestDigest()); + record.put("state", PENDING); + record.put("authorityTuple", claims.get("authorityTuple")); + record.put("membershipVersion", claims.get("membershipVersion")); + record.put("issuanceFence", issuanceFence); + record.put("authoritySourceVersions", snapshot.sourceVersions()); + record.put("authEvidenceBundle", evidenceBundleReference.toMap()); + + GameSessionAccountDelegationRegistryRecord result = + new GameSessionAccountDelegationRegistryRecord(record); + result.toCanonicalJsonBytes(maxRecordBytes); + return result; + } + + /** Decodes a supported canonical registry value without granting it authority. */ + public static GameSessionAccountDelegationRegistryRecord decode( + byte[] canonicalUtf8, long maxRecordBytes) { + Objects.requireNonNull(canonicalUtf8, "Registry bytes are required"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + if (canonicalUtf8.length == 0 || canonicalUtf8.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + String json = strictUtf8(canonicalUtf8); + byte[] canonical = canonicalize(json); + if (!Arrays.equals(canonicalUtf8, canonical)) { + throw invalid("Registry value is not canonical RFC 8785 UTF-8"); + } + Map decoded = parseObject(json, "registry record"); + requireExactFields( + decoded, fieldsFor(RECORD_FIELDS, decoded.containsKey("tenantId")), "registry record"); + validateRecord(decoded); + return new GameSessionAccountDelegationRegistryRecord(decoded); + } + + /** Returns canonical RFC 8785 record bytes, subject to both the caller and profile ceilings. */ + public byte[] toCanonicalJsonBytes(long maxRecordBytes) { + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + byte[] canonical = canonicalize(serialize(fields)); + if (canonical.length == 0 || canonical.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + return canonical; + } + + public String tokenHash() { + return textField("tokenHash"); + } + + public String kid() { + return textField("kid"); + } + + public String signerGeneration() { + return textField("signerGeneration"); + } + + public String accountId() { + return textField("accountId"); + } + + public String jti() { + return textField("jti"); + } + + public String operationId() { + return textField("operationId"); + } + + public String requestId() { + return textField("requestId"); + } + + public String requestDigest() { + return textField("requestDigest"); + } + + public String state() { + return textField("state"); + } + + public long issuedAtEpochSecond() { + return requirePositiveInteger(fields.get("iat"), "iat"); + } + + public long notBeforeEpochSecond() { + return requirePositiveInteger(fields.get("nbf"), "nbf"); + } + + public long issuanceFence() { + return requirePositiveDecimalLong(fields.get("issuanceFence"), "issuanceFence"); + } + + public long registryVersion() { + return requirePositiveInteger(fields.get("registryVersion"), "registryVersion"); + } + + public EvidenceBundleReference evidenceBundleReference() { + Map value = + requireObject(fields.get("authEvidenceBundle"), "authEvidenceBundle"); + return new EvidenceBundleReference( + requirePositiveDecimal(value.get("bundleVersion"), "bundleVersion"), + requirePositiveDecimal(value.get("sourceVersion"), "sourceVersion"), + requirePositiveDecimal(value.get("sourceFence"), "sourceFence"), + requirePositiveLinearization(value.get("linearization")), + requireMatchValue(HASH, value.get("canonicalSha256"), "canonicalSha256")); + } + + public long expiresAtEpochSecond() { + return requirePositiveInteger(fields.get("exp"), "exp"); + } + + public Map fields() { + return immutableMap(fields); + } + + private String textField(String field) { + return requireText(fields.get(field), field, 256); + } + + private static Set fieldsFor(Set initial, boolean bound) { + if (!bound) return initial; + var fields = new java.util.HashSet<>(initial); + fields.add("tenantId"); + return Set.copyOf(fields); + } + + private static void validateRecord(Map record) { + requireExactInteger(record.get("schemaVersion"), SCHEMA_VERSION, "schemaVersion"); + long registryVersion = requirePositiveInteger(record.get("registryVersion"), "registryVersion"); + String state = requireText(record.get("state"), "state", 16); + if (PENDING.equals(state)) { + if (registryVersion != PENDING_REGISTRY_VERSION) { + throw invalid("pending registry version mismatch"); + } + } else if (ACTIVE.equals(state)) { + if (registryVersion != ACTIVE_REGISTRY_VERSION) { + throw invalid("active registry version mismatch"); + } + } else { + throw invalid("Unsupported registry lifecycle state"); + } + requireMatch(HASH, record.get("tokenHash"), "tokenHash"); + requireMatch(HASH, record.get("requestDigest"), "requestDigest"); + requireCanonicalUuid(record.get("jti"), "jti"); + requireCanonicalUuid(record.get("operationId"), "operationId"); + requireCanonicalUuid(record.get("requestId"), "requestId"); + requireMatch(KID, record.get("kid"), "kid"); + requirePositiveDecimal(record.get("signerGeneration"), "signerGeneration"); + requireEqual(GameSessionAccountDelegationProfile.ISSUER, record.get("issuer"), "issuer"); + requireEqual(GameSessionAccountDelegationProfile.PROFILE, record.get("profile"), "profile"); + requireEqual(GameSessionAccountDelegationProfile.TYPE, record.get("type"), "type"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, record.get("audience"), "audience"); + String accountId = requireCanonicalUuid(record.get("accountId"), "accountId"); + long issuedAt = requirePositiveInteger(record.get("iat"), "iat"); + long notBefore = requirePositiveInteger(record.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(record.get("exp"), "exp"); + requireEqual( + "1", + requirePositiveDecimal(record.get("tokenGeneration"), "tokenGeneration"), + "initial token generation mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, 0L); + Map tuple = requireObject(record.get("authorityTuple"), "authorityTuple"); + String accountGeneration = + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boolean hasCutoff = tuple.containsKey("accountSecurityCutoff"); + if (hasCutoff != !"1".equals(accountGeneration)) { + throw invalid("Account security cutoff presence does not match the source generation"); + } + Set tupleFields = + new java.util.HashSet<>( + hasCutoff ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF : AUTHORITY_TUPLE_FIELDS); + if (record.containsKey("tenantId") && tuple.containsKey("tenantBillingCutoff")) + tupleFields.add("tenantBillingCutoff"); + requireExactFields(tuple, tupleFields, "authorityTuple"); + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + if (record.containsKey("tenantId")) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + requireCanonicalUuid(record.get("tenantId"), "tenantId"), + tuple, + requireObject(record.get("membershipVersion"), "membershipVersion")); + } else { + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject( + tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + } + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (hasCutoff) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + String cutoffSequence = + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + String cutoffStream = requireText(cutoff.get("outboxStreamKey"), "cutoff stream", 2048); + long accountGenerationValue = + requirePositiveDecimalLong(accountGeneration, "account generation"); + if (!accountGeneration.equals(cutoffGeneration) + || !Long.toString(accountGenerationValue - 1L).equals(cutoffSequence) + || !("account:auth-authority:v1:account/" + accountId).equals(cutoffStream)) { + throw invalid("Account security cutoff scope or sequence is invalid"); + } + } + if (!record.containsKey("tenantId")) + requireEmptyObject(record.get("membershipVersion"), "membershipVersion"); + requirePositiveDecimal(record.get("issuanceFence"), "issuanceFence"); + Map versions = + requireObject(record.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + Map bundle = + requireObject(record.get("authEvidenceBundle"), "authEvidenceBundle"); + requireExactFields( + bundle, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization", "canonicalSha256"), + "authEvidenceBundle"); + requirePositiveDecimal(bundle.get("bundleVersion"), "bundleVersion"); + requirePositiveDecimal(bundle.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(bundle.get("sourceFence"), "sourceFence"); + requirePositiveLinearization(bundle.get("linearization")); + requireMatch(HASH, bundle.get("canonicalSha256"), "canonicalSha256"); + } + + private static void validateAuthorityTuple( + Object tupleValue, Object membershipVersionValue, AccountAuthoritySnapshot snapshot) { + Map tuple = requireObject(tupleValue, "authorityTuple"); + Set expectedFields = + snapshot.accountSecurityCutoff().isPresent() + ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF + : AUTHORITY_TUPLE_FIELDS; + requireExactFields(tuple, expectedFields, "authorityTuple"); + if (canonicalize(serialize(tuple)).length + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw invalid("authorityTuple exceeds its finite profile byte bound"); + } + requireEqual( + Long.toString(snapshot.issuerGeneration()), + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"), + "issuer authority generation mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"), + "Account authority generation mismatch"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (snapshot.accountSecurityCutoff().isPresent()) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + requireText(cutoff.get("outboxStreamKey"), "cutoff outboxStreamKey", 2048); + if (!snapshot.accountSecurityCutoff().orElseThrow().toMap().equals(cutoff)) { + throw invalid("Account security cutoff does not match the source snapshot"); + } + } + requireEmptyObject(membershipVersionValue, "membershipVersion"); + } + + private static CompactToken parseCompactJwt(String compactJwt) { + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + if (compactJwt.length() == 0 + || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compactBytes.length != compactJwt.length()) { + throw invalid("Compact JWT is absent or exceeds its profile byte bound"); + } + String[] parts = compactJwt.split("\\.", -1); + if (parts.length != 3 || Arrays.stream(parts).anyMatch(String::isEmpty)) { + throw invalid("Compact JWT is malformed"); + } + byte[] headerBytes = decodeBase64Url(parts[0]); + byte[] claimsBytes = decodeBase64Url(parts[1]); + decodeBase64Url(parts[2]); + Map header = parseObject(strictUtf8(headerBytes), "JOSE header"); + Set headerFields = header.keySet(); + if (!HEADER_ALLOWED.containsAll(headerFields) || !headerFields.containsAll(HEADER_REQUIRED)) { + throw invalid("JOSE header fields are not the exact supported set"); + } + requireEqual("RS256", header.get("alg"), "Account delegation must use RS256"); + String kid = requireText(header.get("kid"), "kid", 64); + requireMatch(KID, kid, "kid"); + if (header.containsKey("typ")) requireEqual("JWT", header.get("typ"), "typ"); + Map claims = parseObject(strictUtf8(claimsBytes), "JWT claims"); + return new CompactToken(kid, claims); + } + + private static void validateTimeWindow(long issuedAt, long notBefore, long expiresAt, long now) { + long lifetime; + try { + lifetime = Math.subtractExact(expiresAt, issuedAt); + } catch (ArithmeticException ex) { + throw invalid("JWT time bounds are invalid or expired"); + } + long latestAllowedIssuedAt = now; + if (now > 0L) { + try { + latestAllowedIssuedAt = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestAllowedIssuedAt = Long.MAX_VALUE; + } + } + if (notBefore > issuedAt + || lifetime <= 0L + || lifetime > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + || (now > 0L && (issuedAt > latestAllowedIssuedAt || expiresAt <= now))) { + throw invalid("JWT time bounds are invalid or expired"); + } + } + + private static byte[] decodeBase64Url(String value) { + try { + if (value.indexOf('=') >= 0 || !value.matches("[A-Za-z0-9_-]+")) + throw invalid("JWT segment is not base64url"); + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + throw invalid("JWT segment has a non-canonical base64url encoding"); + } + return decoded; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid("JWT segment is malformed"); + } + } + + private static Map parseObject(String json, String field) { + try { + Map parsed = JSON.readValue(json, new TypeReference<>() {}); + if (parsed == null || parsed.isEmpty()) throw invalid(field + " must be a non-empty object"); + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is malformed"); + } + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map map)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null || result.put(name, item) != null) { + throw invalid(field + " contains an invalid member"); + } + }); + return result; + } + + private static Map immutableMap(Map input) { + Map copy = new LinkedHashMap<>(); + input.forEach( + (key, value) -> { + if (key == null || value == null) throw invalid("Null registry field is forbidden"); + copy.put(key, deepImmutable(value)); + }); + return Map.copyOf(copy); + } + + private static Object deepImmutable(Object value) { + if (value instanceof Map map) { + Map nested = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null) { + throw invalid("Null or invalid nested registry field is forbidden"); + } + nested.put(name, deepImmutable(item)); + }); + return Map.copyOf(nested); + } + if (value instanceof List list) { + return list.stream().map(GameSessionAccountDelegationRegistryRecord::deepImmutable).toList(); + } + return value; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected)) throw invalid(field + " has missing or unknown fields"); + if (value.values().stream().anyMatch(Objects::isNull)) throw invalid(field + " contains null"); + } + + private static void requireEmptyObject(Object value, String field) { + if (!(value instanceof Map map) || !map.isEmpty()) + throw invalid(field + " must be an empty object"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) + throw invalid(field + " must be an empty list"); + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw invalid(field + " must be a bounded positive integer"); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw invalid(field + " must be a bounded positive integer"); + } + } + + private static long requirePositiveDecimalLong(Object value, String field) { + String decimal = requirePositiveDecimal(value, field); + try { + return Long.parseLong(decimal); + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requirePositiveDecimal(Object value, String field) { + if (!(value instanceof String string) || !POSITIVE_DECIMAL.matcher(string).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + Long.parseLong(string); + return string; + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static String requireCanonicalUuid(Object value, String field) { + String text = requireText(value, field, 36); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) + throw invalid(field + " is not a canonical UUID"); + return text; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is not a canonical UUID"); + } + } + + private static String requireText(Object value, String field, int maxLength) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > maxLength) { + throw invalid(field + " must be a bounded non-empty string"); + } + for (int i = 0; i < text.length(); i++) { + if (Character.isISOControl(text.charAt(i))) + throw invalid(field + " contains a control character"); + } + return text; + } + + private static void requireMatch(Pattern pattern, Object value, String field) { + if (!(value instanceof String text) || !pattern.matcher(text).matches()) + throw invalid(field + " has an invalid format"); + } + + private static String requireMatchValue(Pattern pattern, Object value, String field) { + requireMatch(pattern, value, field); + return (String) value; + } + + private static String requirePositiveLinearization(Object value) { + if (!(value instanceof String text) || !POSITIVE_LINEARIZATION.matcher(text).matches()) { + throw invalid("bundle linearization is malformed"); + } + return text; + } + + private static void requireExactInteger(Object value, long expected, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be an integer"); + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) { + throw invalid(field + " is unsupported"); + } + try { + if (Long.parseLong(encoded) != expected) throw invalid(field + " is unsupported"); + } catch (NumberFormatException ex) { + throw invalid(field + " is unsupported"); + } + } + + private static void requireEqual(Object expected, Object actual, String message) { + if (!Objects.equals(expected, actual)) throw invalid(message); + } + + private static void requireBound(long value, long maximum, String field) { + if (value <= 0L || value > maximum) + throw invalid(field + " is outside the finite profile bound"); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("JWT/registry JSON is not valid UTF-8"); + } + } + + private static String serialize(Object value) { + try { + return JSON.writeValueAsString(value); + } catch (RuntimeException ex) { + throw invalid("Registry JSON could not be serialized"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("RFC 8785 canonicalization failed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static InvalidRecordException invalid(String message) { + return new InvalidRecordException(message); + } + + private record CompactToken(String keyId, Map claims) {} + + public record AccountAuthoritySnapshot( + UUID accountId, + long issuerGeneration, + long issuerSourceVersion, + long accountGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + Optional accountSecurityCutoff) { + public AccountAuthoritySnapshot { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required"); + if (accountId.equals(new UUID(0L, 0L)) + || issuerGeneration <= 0L + || issuerSourceVersion <= 0L + || accountGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || issuerGeneration != issuerSourceVersion + || accountGeneration != accountSourceVersion + || accountGeneration != issuanceFence + || accountGeneration != issuanceFenceSourceVersion) { + throw invalid("Durable Account authority snapshot is malformed"); + } + String expectedStream = "account:auth-authority:v1:account/" + accountId; + if (accountGeneration == 1L) { + if (accountSecurityCutoff.isPresent()) { + throw invalid("Fresh sequence-zero Account authority cannot carry a cutoff"); + } + } else { + GameSessionAccountDelegationProfile.AccountSecurityCutoff cutoff = + accountSecurityCutoff.orElseThrow( + () -> invalid("Advanced Account authority requires its source cutoff")); + if (!Long.toString(accountGeneration).equals(cutoff.accountAuthorityGeneration()) + || !expectedStream.equals(cutoff.outboxStreamKey()) + || !Long.toString(accountGeneration - 1L).equals(cutoff.outboxSequence())) { + throw invalid("Account security cutoff scope or sequence is stale"); + } + } + } + + public Map sourceVersions() { + return Map.of( + "issuerSourceVersion", Long.toString(issuerSourceVersion), + "accountSourceVersion", Long.toString(accountSourceVersion), + "issuanceFenceSourceVersion", Long.toString(issuanceFenceSourceVersion)); + } + } + + public record IssuanceBinding( + String operationId, String requestId, String requestDigest, String accountId) { + public IssuanceBinding { + requireCanonicalUuid(operationId, "operationId"); + requireCanonicalUuid(requestId, "requestId"); + requireMatch(HASH, requestDigest, "requestDigest"); + requireCanonicalUuid(accountId, "accountId"); + } + } + + /** Exact immutable V46 bundle reference and digest bound into the registry projection. */ + public record EvidenceBundleReference( + String bundleVersion, + String sourceVersion, + String sourceFence, + String linearization, + String canonicalSha256) { + public EvidenceBundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveLinearization(linearization); + requireMatch(HASH, canonicalSha256, "canonicalSha256"); + } + + public Map toMap() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization, + "canonicalSha256", canonicalSha256); + } + } + + public static final class InvalidRecordException extends IllegalArgumentException { + public InvalidRecordException(String message) { + super(message); + } + } +} + diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java new file mode 100644 index 0000000000..4eab9411e3 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.common.security; + +import java.util.Map; +import java.util.Set; + +/** Validates the canonical, tenant-free player-bootstrap JWT claim shape. */ +public final class PlayerBootstrapJwtProfileValidator { + public static final String PROFILE = "player-bootstrap"; + public static final String AUDIENCE = "player-bootstrap"; + public static final String TOKEN_TYPE = "player-bootstrap"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private PlayerBootstrapJwtProfileValidator() {} + + /** Checks profile shape only; it does not validate current membership or authorize a route. */ + public static void validateClaims(Map claims) { + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), false, true, false); + if (!AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")).isEmpty() + || !AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")).isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } +} + diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java new file mode 100644 index 0000000000..f33d68c204 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ControlUiJwtProfileValidatorTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_A = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_B = "33333333-3333-4333-8333-333333333333"; + + @Test + void acceptsSeparateTargetAndMembershipApplicabilityAndOptionalGlobalRoles() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + claims.put("globalRoles", List.of()); + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void preservesProfileSpecificOptionalAccountCutoffOmission() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put("accountAuthorityGeneration", 2L); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsMismatchedMembershipPairMalformedScopeAndEmptyPresentOptionalObject() { + Map mismatch = validClaims(); + mismatch.put("membershipVersion", Map.of(TENANT_A, 8L)); + assertInvalid(mismatch); + + Map badScope = validClaims(); + badScope.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(badScope); + + Map emptyBillingObject = validClaims(); + Map tuple = object(emptyBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", Map.of()); + emptyBillingObject.put("authorityTuple", tuple); + assertInvalid(emptyBillingObject); + + Map nullBillingObject = validClaims(); + tuple = object(nullBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", null); + nullBillingObject.put("authorityTuple", tuple); + assertInvalid(nullBillingObject); + + Map malformedRole = validClaims(); + malformedRole.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin", "tenantAdmin"))); + assertInvalid(malformedRole); + assertInvalid(Map.of("unexpected", true)); + } + + @Test + void sharedConfiguredScopeCapBoundsEveryControlUiApplicabilityMap() { + Map tooManyScopedRoles = validClaims(); + tooManyScopedRoles.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyScopedRoles, 1); + + Map tooManyTenantGenerations = validClaims(); + Map tenantTuple = object(tooManyTenantGenerations.get("authorityTuple")); + tenantTuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyTenantGenerations.put("authorityTuple", tenantTuple); + tooManyTenantGenerations.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyTenantGenerations, 1); + + Map tooManyMembershipGenerations = validClaims(); + Map membershipTuple = + object(tooManyMembershipGenerations.get("authorityTuple")); + membershipTuple.put("membershipAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyMembershipGenerations.put("authorityTuple", membershipTuple); + tooManyMembershipGenerations.put("membershipVersion", Map.of(TENANT_A, 7L, TENANT_B, 8L)); + tooManyMembershipGenerations.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + assertInvalidAtCap(tooManyMembershipGenerations, 1); + + Map tooManyBillingCutoffs = validClaims(); + Map billingTuple = object(tooManyBillingCutoffs.get("authorityTuple")); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", 2L, + "tenantBillingSequence", 3L, + "outboxStreamKey", "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", 4L); + billingTuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff, TENANT_B, cutoff)); + tooManyBillingCutoffs.put("authorityTuple", billingTuple); + tooManyBillingCutoffs.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyBillingCutoffs, 1); + } + + @Test + void eachControlUiApplicabilityMapAcceptsTheExactConfiguredCap() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_A, + Map.of( + "tenantAuthorityGeneration", + 2L, + "tenantBillingSequence", + 3L, + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", + 4L))); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void nilAndAccountIdTenantKeysAreRejectedAsMalformedProfileKeys() { + Map nilAccount = validClaims(); + nilAccount.put("sub", "00000000-0000-0000-0000-000000000000"); + nilAccount.put("accountId", "00000000-0000-0000-0000-000000000000"); + assertInvalid(nilAccount); + + Map accountKey = validClaims(); + Map tuple = object(accountKey.get("authorityTuple")); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, 2L)); + accountKey.put("authorityTuple", tuple); + accountKey.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(accountKey); + } + + @Test + void canonicalAuthorityTupleByteCeilingIsEnforcedAfterTheFiniteCountCap() { + Map tenantGenerations = new LinkedHashMap<>(); + Map> scopedRoles = new LinkedHashMap<>(); + for (int index = 0; index < 100; index++) { + String tenantId = UUID.randomUUID().toString(); + tenantGenerations.put(tenantId, 1L); + scopedRoles.put(tenantId, List.of("reader")); + } + Map claims = baseClaims(); + claims.put("authorityTuple", authorityTuple(tenantGenerations, Map.of(), List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", scopedRoles); + + assertInvalidAtCap(claims, 128); + } + + private static Map validClaims() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + return claims; + } + + private static Map baseClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", 1L); + claims.put("issuanceFence", 1L); + return claims; + } + + private static Map authorityTuple( + Map tenantGenerations, + Map membershipGenerations, + List privateGrants) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", 1L); + tuple.put("accountAuthorityGeneration", 1L); + tuple.put("tenantAuthorityGeneration", tenantGenerations); + tuple.put("membershipAuthorityGeneration", membershipGenerations); + tuple.put("privateRealmGrantVersions", privateGrants); + return tuple; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, 8)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } + + private static void assertInvalidAtCap(Map claims, int cap) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, cap)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +} + diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java new file mode 100644 index 0000000000..a3a3b914d9 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** Durable, bounded Logging/Admin claim lifecycle for the StartSession pre-authorization phase. */ +@Service +public final class StartSessionPreAuthorizationReservationService { + public static final Duration CLAIM_TTL = Duration.ofSeconds(30); + + private final StartSessionPreAuthorizationReservationRepository repository; + private final Clock clock; + + @Autowired + public StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository) { + this(repository, Clock.systemUTC()); + } + + StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + this.repository = Objects.requireNonNull(repository, "repository is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Atomically creates one reservation or returns the exact existing reservation as a duplicate. + * Only the first caller receives a claim capability; an exact duplicate cannot dispatch work. + */ + public Acquisition acquire(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an actor derived from the authenticated request context"); + } + Instant now = clock.instant(); + UUID ownerId = UUID.randomUUID(); + StartSessionPreAuthorizationReservationRepository.AcquireResult result = + repository.acquire(tuple, ownerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + ClaimHandle claim = + result.created() + ? new ClaimHandle( + tuple, + tuple.mutationDigest(), + ownerId, + ownerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimKind.ORIGINAL) + : null; + return new Acquisition(result.snapshot(), claim); + } + + /** Read-only lookup by the one stable orchestration key. */ + public Optional find(String controlPlaneRequestId) { + return repository.find(controlPlaneRequestId); + } + + /** Read-only exact lookup; a reused key with any tuple difference conflicts. */ + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findExact(tuple); + } + + /** + * Durably enters AUTHORIZATION_PENDING before the Account call is dispatched by a later + * integration. Only the first successful transition returns {@code mayDispatch=true}; observing + * the pending state again never authorizes another issuance call. + */ + public PendingTransition markAuthorizationPending(ClaimHandle claim) { + requireClaim(claim); + if (claim.isRecoveryLookupOnly()) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.TransitionResult result = + repository.markAuthorizationPending( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + epochMillis(clock.instant())); + return new PendingTransition(result.snapshot(), result.transitioned()); + } + + /** Renew only the exact current, active claim before its expiry. */ + public Snapshot renew(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireClaim(claim); + Instant now = clock.instant(); + return repository.renew( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(now), + epochMillis(now.plus(CLAIM_TTL))); + } + + /** + * Advance the current fence after the exact claim expires. Expiry leaves the phase and state + * unchanged; it is not evidence that Account authorization did not happen. + */ + public Snapshot expireClaim(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireClaim(claim); + return repository.expireClaim( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(clock.instant())); + } + + /** + * Acquire one fresh recovery claim only for an expired AUTHORIZATION_PENDING reservation. The + * returned claim is suitable only for a future read-only Account recovery lookup; it cannot + * initiate issuance or authorize owner forwarding. Original reservation owner/fence evidence is + * preserved in the row and snapshot. + */ + public Optional acquireAuthorizationRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + Instant now = clock.instant(); + UUID recoveryOwnerId = UUID.randomUUID(); + Optional acquired = + repository.acquireRecoveryClaim( + tuple, recoveryOwnerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + return acquired.map( + result -> + new RecoveryAcquisition( + result.snapshot(), + new ClaimHandle( + tuple, + tuple.mutationDigest(), + result.reservationOwnerId(), + recoveryOwnerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimKind.RECOVERY_LOOKUP_ONLY))); + } + + private static void requireClaim(ClaimHandle claim) { + Objects.requireNonNull(claim, "claim is required"); + } + + private static long epochMillis(Instant instant) { + long millis = instant.toEpochMilli(); + if (millis <= 0) { + throw new IllegalArgumentException("reservation time must be after the Unix epoch"); + } + return millis; + } + + public enum Phase { + ACCOUNT_AUTHORIZATION + } + + public enum State { + RESERVED, + AUTHORIZATION_PENDING + } + + public enum ClaimState { + ACTIVE, + EXPIRED + } + + private enum ClaimKind { + ORIGINAL, + RECOVERY_LOOKUP_ONLY + } + + public record Snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + Phase phase, + State state, + long reservationClaimFence, + long claimFence, + long claimExpiresAtEpochMillis, + ClaimState claimState) { + public Snapshot { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + Objects.requireNonNull(phase, "phase is required"); + Objects.requireNonNull(state, "state is required"); + Objects.requireNonNull(claimState, "claimState is required"); + if (reservationClaimFence != 1 || claimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + if (claimExpiresAtEpochMillis <= 0) { + throw new IllegalArgumentException("claim expiry must be positive"); + } + if (!tuple.mutationDigest().equals(mutationDigest)) { + throw new IllegalArgumentException("stored mutationDigest does not match the typed tuple"); + } + } + } + + /** Opaque capability returned only to the caller that acquired a new claim. */ + public static final class ClaimHandle { + private final StartSessionPreAuthorizationReservationTuple tuple; + private final String mutationDigest; + private final UUID reservationOwnerId; + private final UUID ownerId; + private final long reservationFence; + private final long fence; + private final ClaimKind kind; + + private ClaimHandle( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + UUID ownerId, + long reservationFence, + long fence, + ClaimKind kind) { + this.tuple = Objects.requireNonNull(tuple, "tuple is required"); + this.mutationDigest = Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + this.reservationOwnerId = + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + this.ownerId = Objects.requireNonNull(ownerId, "ownerId is required"); + this.reservationFence = reservationFence; + this.fence = fence; + this.kind = Objects.requireNonNull(kind, "claim kind is required"); + if (reservationOwnerId.equals(new UUID(0L, 0L)) + || ownerId.equals(new UUID(0L, 0L)) + || reservationFence <= 0 + || fence < reservationFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + } + + public String controlPlaneRequestId() { + return tuple.controlPlaneRequestId(); + } + + public long claimFence() { + return fence; + } + + public StartSessionPreAuthorizationReservationTuple tuple() { + return tuple; + } + + public String mutationDigest() { + return mutationDigest; + } + + /** Original tuple owner/fence and current fenced claim, kept distinct during recovery. */ + public ClaimEvidence claimEvidence() { + return new ClaimEvidence(reservationOwnerId, reservationFence, ownerId, fence); + } + + public boolean isRecoveryLookupOnly() { + return kind == ClaimKind.RECOVERY_LOOKUP_ONLY; + } + } + + public record Acquisition(Snapshot snapshot, ClaimHandle claim) { + public Acquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (claim != null + && (claim.kind != ClaimKind.ORIGINAL + || snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.RESERVED + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest))) { + throw new IllegalArgumentException("initial claim does not match its reservation"); + } + } + + public boolean newlyAcquired() { + return claim != null; + } + } + + public static final class PendingTransition { + private final Snapshot snapshot; + private final boolean mayDispatchAccountAuthorization; + + private PendingTransition(Snapshot snapshot, boolean mayDispatchAccountAuthorization) { + this.snapshot = Objects.requireNonNull(snapshot, "snapshot is required"); + this.mayDispatchAccountAuthorization = mayDispatchAccountAuthorization; + if (snapshot.state() != State.AUTHORIZATION_PENDING && mayDispatchAccountAuthorization) { + throw new IllegalArgumentException("dispatch requires durable AUTHORIZATION_PENDING state"); + } + } + + public Snapshot snapshot() { + return snapshot; + } + + public boolean mayDispatchAccountAuthorization() { + return mayDispatchAccountAuthorization; + } + } + + public record RecoveryAcquisition(Snapshot snapshot, ClaimHandle claim) { + public RecoveryAcquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim is required"); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING + || snapshot.claimState() != ClaimState.ACTIVE + || !claim.isRecoveryLookupOnly() + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest)) { + throw new IllegalArgumentException( + "recovery claim is not read-only authorization recovery"); + } + } + } + + public record ClaimEvidence( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + public ClaimEvidence { + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + if (reservationClaimFence != 1 || currentClaimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim evidence is invalid"); + } + } + } + + public static class IdempotencyConflictException extends RuntimeException { + public IdempotencyConflictException(String controlPlaneRequestId) { + super( + "controlPlaneRequestId is already bound to a different StartSession tuple: " + + controlPlaneRequestId); + } + } + + public static class StaleReservationClaimException extends RuntimeException { + public StaleReservationClaimException(String controlPlaneRequestId) { + super("StartSession reservation claim is stale: " + controlPlaneRequestId); + } + } + + public static class ReservationClaimNotExpiredException extends RuntimeException { + public ReservationClaimNotExpiredException(String controlPlaneRequestId) { + super("StartSession reservation claim has not expired: " + controlPlaneRequestId); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..74ea3a3da5 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; + +/** Logging/Admin authority wrapper around the shared immutable StartSession tuple value. */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_ID; + public static final String TUPLE_SCHEMA_VERSION = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_VERSION; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES; + + private final net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + value; + private final boolean authorityDerived; + + private StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple value, + boolean authorityDerived) { + this.value = Objects.requireNonNull(value, "tuple value is required"); + this.authorityDerived = authorityDerived; + } + + /** Builds the tuple from the current authenticated tenant-admin request context. */ + public static StartSessionPreAuthorizationReservationTuple fromCurrentTenantAdmin( + String controlPlaneRequestId, StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + if (SessionContext.isInternalService() || !SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalArgumentException("a human control-ui identity is required"); + } + String tenantId = action.scope().tenantId().toString(); + if (!SessionContext.getScopedRoles(tenantId).contains("tenantAdmin")) { + throw new IllegalArgumentException("tenantAdmin authority is required for the target tenant"); + } + UUID actorAccountId = requireCanonicalUuid(SessionContext.getAccountId(), "actor accountId"); + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(controlPlaneRequestId, actorAccountId, action), + true); + } + + /** Rehydrates only tuple contents; persisted bytes do not establish request authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(json), + false); + } + + public String actionFamily() { + return value.actionFamily(); + } + + public String controlPlaneRequestId() { + return value.controlPlaneRequestId(); + } + + public HumanActor actor() { + return new HumanActor(value.actor().accountId()); + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return value.action(); + } + + public boolean isAuthorityDerived() { + return authorityDerived; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .requireCanonicalControlPlaneRequestId(value); + } + + public String targetOwner() { + return value.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return value.mutationDigest(); + } + + /** Returns the single shared canonical encoding for ADR 0048's typed tuple. */ + public String canonicalJson() { + return value.canonicalJson(); + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof StartSessionPreAuthorizationReservationTuple that + && value.equals(that.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + private static UUID requireCanonicalUuid(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java new file mode 100644 index 0000000000..4c32e3a97c --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -0,0 +1,415 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +/** jOOQ persistence for the single-key StartSession ADR 0048 reservation phase. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class StartSessionPreAuthorizationReservationRepository { + private static final StartSessionPreAuthorizationReservations TABLE = + START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + + private final DSLContext dsl; + + public StartSessionPreAuthorizationReservationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, + UUID ownerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an authority-derived StartSession tuple"); + } + String tupleJson = tuple.canonicalJson(); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int inserted = + tx.insertInto(TABLE) + .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) + .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) + .set(TABLE.MUTATION_DIGEST, mutationDigest) + .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) + .set(TABLE.STATE, State.RESERVED.name()) + .set(TABLE.RESERVATION_OWNER_ID, ownerId) + .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_OWNER_ID, ownerId) + .set(TABLE.CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new IllegalStateException("reservation row was not visible after acquire"); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + return new AcquireResult(snapshot, inserted == 1); + }); + } + + public Optional find(String controlPlaneRequestId) { + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + return dsl.selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .fetchOptional(this::toSnapshot); + } + + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + return find(tuple.controlPlaneRequestId()) + .map( + snapshot -> { + if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService + .IdempotencyConflictException(tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + long nowEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.RESERVED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(ownerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(1L)) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return new TransitionResult(snapshot, true); + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Snapshot renew( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated != 1) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public Snapshot expireClaim( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .setNull(TABLE.CLAIM_OWNER_ID) + .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) + .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return snapshot; + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { + throw new StartSessionPreAuthorizationReservationService + .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Optional acquireRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwnerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + String previousClaimState = row.get(TABLE.CLAIM_STATE); + long previousFence = row.get(TABLE.CLAIM_FENCE); + long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); + if (!ClaimState.EXPIRED.name().equals(previousClaimState) + && !(ClaimState.ACTIVE.name().equals(previousClaimState) + && previousExpiry <= nowEpochMillis)) { + return Optional.empty(); + } + long recoveryFence = Math.addExact(previousFence, 1L); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) + .set(TABLE.CLAIM_FENCE, recoveryFence) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) + .and(TABLE.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .and( + ClaimState.EXPIRED.name().equals(previousClaimState) + ? DSL.trueCondition() + : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + if (updated != 1) { + return Optional.empty(); + } + Record updatedRow = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (updatedRow == null) { + throw new IllegalStateException("recovery claim row disappeared after update"); + } + return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); + }); + } + + private Record lockByRequestId(DSLContext context, String controlPlaneRequestId) { + return context + .selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .forUpdate() + .fetchOne(); + } + + private void requireBoundedClaim(UUID ownerId, long nowEpochMillis, long expiresAtEpochMillis) { + requireClaimOwner(ownerId, 1L, nowEpochMillis); + if (expiresAtEpochMillis <= nowEpochMillis + || expiresAtEpochMillis - nowEpochMillis + > StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()) { + throw new IllegalArgumentException("reservation claim must have a bounded positive expiry"); + } + } + + private void requireClaimOwner(UUID ownerId, long claimFence, long nowEpochMillis) { + if (ownerId == null + || ownerId.equals(new UUID(0L, 0L)) + || claimFence <= 0L + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation claim identity and time must be positive"); + } + } + + private Snapshot toSnapshot(Record row) { + String requestId = row.get(TABLE.CONTROL_PLANE_REQUEST_ID); + String tupleJson = row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON); + String storedDigest = row.get(TABLE.MUTATION_DIGEST); + StartSessionPreAuthorizationReservationTuple tuple; + try { + tuple = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "stored StartSession pre-authorization tuple is malformed for " + requestId, exception); + } + if (!requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "stored StartSession tuple key does not match reservation key " + requestId); + } + String recomputedDigest = tuple.mutationDigest(); + if (!recomputedDigest.equals(storedDigest)) { + throw new IllegalStateException( + "stored StartSession mutationDigest does not match its full tuple for " + requestId); + } + Phase phase = enumValue(Phase.class, row.get(TABLE.PHASE), "phase", requestId); + State state = enumValue(State.class, row.get(TABLE.STATE), "state", requestId); + ClaimState claimState = + enumValue(ClaimState.class, row.get(TABLE.CLAIM_STATE), "claimState", requestId); + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID currentClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + long originalFence = row.get(TABLE.RESERVATION_CLAIM_FENCE); + long currentFence = row.get(TABLE.CLAIM_FENCE); + long createdAt = row.get(TABLE.CREATED_AT_EPOCH_MS); + long updatedAt = row.get(TABLE.UPDATED_AT_EPOCH_MS); + if (phase != Phase.ACCOUNT_AUTHORIZATION + || (state != State.RESERVED && state != State.AUTHORIZATION_PENDING) + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || originalFence != 1L + || currentFence < originalFence + || createdAt <= 0L + || updatedAt <= 0L + || (claimState == ClaimState.ACTIVE + && (currentClaimOwnerId == null || currentClaimOwnerId.equals(new UUID(0L, 0L)))) + || (claimState == ClaimState.EXPIRED + && (currentClaimOwnerId != null || currentFence <= originalFence))) { + throw new IllegalStateException("stored StartSession reservation lifecycle is malformed"); + } + return new Snapshot( + tuple, + storedDigest, + phase, + state, + originalFence, + currentFence, + row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS), + claimState); + } + + private void requireExactTuple( + Record row, StartSessionPreAuthorizationReservationTuple tuple, String mutationDigest) { + if (!tuple.controlPlaneRequestId().equals(row.get(TABLE.CONTROL_PLANE_REQUEST_ID)) + || !tuple.canonicalJson().equals(row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON)) + || !tuple.mutationDigest().equals(mutationDigest) + || !mutationDigest.equals(row.get(TABLE.MUTATION_DIGEST))) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + private boolean isCurrentClaim(Record row, UUID ownerId, long claimFence, long nowEpochMillis) { + return ownerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + && claimFence == row.get(TABLE.CLAIM_FENCE) + && ClaimState.ACTIVE.name().equals(row.get(TABLE.CLAIM_STATE)) + && row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS) > nowEpochMillis; + } + + private > T enumValue( + Class enumClass, String value, String fieldName, String requestId) { + try { + return Enum.valueOf(enumClass, value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "stored StartSession reservation " + fieldName + " is invalid for " + requestId, + exception); + } + } + + public record AcquireResult(Snapshot snapshot, boolean created) {} + + public record TransitionResult(Snapshot snapshot, boolean transitioned) {} + + public record RecoveryClaimResult(Snapshot snapshot, UUID reservationOwnerId) {} +} diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql new file mode 100644 index 0000000000..d91510fa3f --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql @@ -0,0 +1,27 @@ +CREATE TABLE start_session_pre_authorization_reservations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY, + pre_authorization_tuple_json VARCHAR(8192) NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + phase VARCHAR(32) NOT NULL + CHECK (phase = 'ACCOUNT_AUTHORIZATION'), + state VARCHAR(40) NOT NULL + CHECK (state IN ('RESERVED', 'AUTHORIZATION_PENDING')), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL + CHECK (reservation_claim_fence = 1), + claim_owner_id UUID, + claim_fence BIGINT NOT NULL + CHECK (claim_fence >= reservation_claim_fence), + claim_expires_at_epoch_ms BIGINT NOT NULL + CHECK (claim_expires_at_epoch_ms > 0), + claim_state VARCHAR(16) NOT NULL + CHECK (claim_state IN ('ACTIVE', 'EXPIRED')), + created_at_epoch_ms BIGINT NOT NULL + CHECK (created_at_epoch_ms > 0), + updated_at_epoch_ms BIGINT NOT NULL + CHECK (updated_at_epoch_ms > 0), + CHECK ( + (claim_state = 'ACTIVE' AND claim_owner_id IS NOT NULL) + OR (claim_state = 'EXPIRED' AND claim_owner_id IS NULL) + ) +); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..e86be465f8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -0,0 +1,252 @@ +package net.firedevops.firemud.loggingadmin; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +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.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class StartSessionPreAuthorizationReservationPostgresIntegrationTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("ffbe29e3-a8d2-4b7d-a046-cf1af57ae904"); + private static final UUID ACTOR_ID = UUID.fromString("4c5b3e92-f60d-4e3d-8b8f-6d89b28495d8"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private StartSessionPreAuthorizationReservationRepository repository; + + @BeforeEach + void migrateAndCreateRepository() { + dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .cleanDisabled(false) + .load() + .clean(); + Flyway.configure().dataSource(dataSource).locations("classpath:db/migration").load().migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new StartSessionPreAuthorizationReservationRepository(dsl); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void concurrentExactAcquiresPersistOneDurableReservationOwner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-01", "same action"); + int callerCount = 8; + ExecutorService executor = Executors.newFixedThreadPool(callerCount); + CountDownLatch ready = new CountDownLatch(callerCount); + CountDownLatch start = new CountDownLatch(1); + List> futures = + new ArrayList<>(); + try { + for (int index = 0; index < callerCount; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent acquire gate timed out"); + } + return acquire(tuple, UUID.randomUUID()); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + List results = + new ArrayList<>(); + for (Future future : + futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + + assertThat(results) + .filteredOn(StartSessionPreAuthorizationReservationRepository.AcquireResult::created) + .hasSize(1); + assertThat(results) + .allSatisfy(result -> assertThat(result.snapshot().tuple()).isEqualTo(tuple)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void sameRequestIdWithChangedTupleConflictsAndFullTupleIsPersisted() { + StartSessionPreAuthorizationReservationTuple original = + tuple("postgres-conflict-02", "same action"); + acquire(original, UUID.randomUUID()); + StartSessionPreAuthorizationReservationTuple changed = + tuple("postgres-conflict-02", "changed audit reason"); + + assertThatThrownBy(() -> acquire(changed, UUID.randomUUID())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + String storedTuple = + dsl.fetchOne( + "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + original.controlPlaneRequestId()) + .get(0, String.class); + assertThat(storedTuple) + .contains(ACTOR_ID.toString()) + .contains("\"ownerService\":\"game-session-service\"") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}"); + } + + @Test + void expiryRecoveryFencesStaleOwnerAndCannotInventTerminalOutcome() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-recovery-03", "recovery fixture"); + UUID originalOwner = UUID.randomUUID(); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + var firstTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(firstTransition.transitioned()).isTrue(); + assertThat(firstTransition.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + var duplicateTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(duplicateTransition.transitioned()).isFalse(); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimFence()).isEqualTo(2L); + assertThat(expired.reservationClaimFence()).isEqualTo(1L); + assertThat(expired.state()).isEqualTo(State.AUTHORIZATION_PENDING); + + assertThatThrownBy( + () -> + repository.renew( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_001L, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + UUID recoveryOwner = UUID.randomUUID(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat( + repository.acquireRecoveryClaim( + tuple, UUID.randomUUID(), NOW_EPOCH_MILLIS + 30_002L, NOW_EPOCH_MILLIS + 60_002L)) + .isEmpty(); + + var recoveredRecord = repository.findExact(tuple).orElseThrow(); + assertThat(recoveredRecord.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(recoveredRecord.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recoveredRecord.reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredRecord.claimFence()).isEqualTo(3L); + assertThat(State.values()).containsExactly(State.RESERVED, State.AUTHORIZATION_PENDING); + } + + @Test + void lookupRecomputesDigestAndRejectsCorruptedStoredEvidence() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-integrity-04", "integrity fixture"); + acquire(tuple, UUID.randomUUID()); + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " + + "WHERE control_plane_request_id = ?", + "0".repeat(64), + tuple.controlPlaneRequestId()); + + assertThatThrownBy(() -> repository.find(tuple.controlPlaneRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mutationDigest"); + } + + private StartSessionPreAuthorizationReservationRepository.AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return repository.acquire(tuple, ownerId, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java new file mode 100644 index 0000000000..6f000f80c8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class StartSessionPreAuthorizationReservationServiceTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"); + private static final UUID ACTOR_ID = UUID.fromString("863843ee-f00a-4905-a9ad-11f706f1b693"); + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private final StartSessionPreAuthorizationReservationService service = + new StartSessionPreAuthorizationReservationService(repository, clock); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void firstAcquisitionGetsOneBoundedClaimAndExactDuplicateGetsNoClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-01"); + Snapshot initial = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, false)); + + Acquisition first = service.acquire(tuple); + Acquisition duplicate = service.acquire(tuple); + + assertThat(first.newlyAcquired()).isTrue(); + assertThat(first.claim()).isNotNull(); + assertThat(first.claim().claimFence()).isEqualTo(1L); + assertThat(duplicate.newlyAcquired()).isFalse(); + assertThat(duplicate.claim()).isNull(); + verify(repository, org.mockito.Mockito.times(2)) + .acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L)); + } + + @Test + void parsedTupleCannotBeUsedAsAnInitialReservationAuthorityAssertion() { + StartSessionPreAuthorizationReservationTuple parsed = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + tuple("service-unit-02").canonicalJson()); + + assertThat(parsed.isAuthorityDerived()).isFalse(); + assertThatThrownBy(() -> service.acquire(parsed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor derived"); + } + + @Test + void expiredPendingClaimCanOnlyBeReacquiredAsReadOnlyRecoveryClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-03"); + Snapshot recovered = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, UUID.fromString("6e0ef777-8661-4139-80eb-904b75de5860")))); + + Optional acquisition = service.acquireAuthorizationRecoveryClaim(tuple); + + assertThat(acquisition).isPresent(); + assertThat(acquisition.orElseThrow().claim().isRecoveryLookupOnly()).isTrue(); + assertThat(acquisition.orElseThrow().snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(acquisition.orElseThrow().snapshot().claimFence()).isEqualTo(3L); + assertThat(acquisition.orElseThrow().snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(acquisition.orElseThrow().claim().claimEvidence().reservationClaimFence()) + .isEqualTo(1L); + assertThat(acquisition.orElseThrow().claim().claimEvidence().currentClaimFence()).isEqualTo(3L); + assertThatThrownBy(() -> service.markAuthorizationPending(acquisition.orElseThrow().claim())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void phaseQualifiedStateModelHasNoSyntheticTerminalOutcome() { + assertThat(State.values()).containsExactly(State.RESERVED, State.AUTHORIZATION_PENDING); + assertThat(Phase.values()).containsExactly(Phase.ACCOUNT_AUTHORIZATION); + } + + @Test + void annotationConfigContextSelectsRepositoryConstructorWithoutDatabase() { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class, () -> repository); + context.register(StartSessionPreAuthorizationReservationService.class); + + try { + context.refresh(); + + assertThat(context.getBean(StartSessionPreAuthorizationReservationService.class)).isNotNull(); + } finally { + context.close(); + } + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long currentFence, + ClaimState claimState) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + currentFence, + NOW_EPOCH_MILLIS + 30_000L, + claimState); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 17L, UUID.fromString("2a9a4d47-a544-4984-bbc4-8e85f84116e4")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test StartSession prerequisite"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..85c8e3a164 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionOperatorActionCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void createsCanonicalHumanOnlyTupleFromCurrentTenantAdminAndPreservesAbsence() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-01", action); + String canonicalJson = tuple.canonicalJson(); + + assertThat(tuple.actor().accountId()).isEqualTo(ACTOR_ID); + assertThat(tuple.isAuthorityDerived()).isTrue(); + assertThat(tuple.automationPolicy()) + .isEqualTo(StartSessionPreAuthorizationReservationTuple.NoAutomationPolicy.ABSENT); + assertThat(tuple.targetOwner()).isEqualTo(StartSessionOperatorAction.OWNER_SERVICE); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(action)); + assertThat(canonicalJson) + .contains("\"requestIdentityKind\":\"controlPlaneRequestId\"") + .contains("\"targetOwner\":{\"ownerService\":\"game-session-service\"}") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}") + .contains("\"automationPolicy\":{\"presence\":\"ABSENT\"}") + .doesNotContain("authorityDerived"); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(canonicalJson); + assertThat(rehydrated).isEqualTo(tuple); + assertThat(rehydrated.isAuthorityDerived()).isFalse(); + assertThat( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(canonicalJson) + .canonicalJson()) + .isEqualTo(canonicalJson); + } + + @Test + void preservesPresentClientIpAsASeparateTypedPresenceValue() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-02", action); + + assertThat(tuple.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tuple.canonicalJson())) + .isEqualTo(tuple); + } + + @Test + void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext(ACTOR_ID.toString(), List.of(), Map.of(), false, null, null); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInternalOrWrongTenantAuthority() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + true, + "logging-admin-service", + "instance-1"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(UUID.randomUUID().toString(), List.of("tenantAdmin")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonCanonicalAndUnsupportedPersistedTupleShapes() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + String canonicalJson = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-05", action(StartSessionOperatorAction.ClientIp.absent())) + .canonicalJson(); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void setTenantAdminContext(UUID tenantId, UUID actorId) { + SessionContext.setContext( + actorId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "approved StartSession prerequisite"); + } +} From dc0230cf6426e1ab9b08fb6bc13ec44b5dc88d18 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:22:36 +1300 Subject: [PATCH 17/29] Use schema-2 participant proof in immutable release publication tests --- .../impl/PublishedWorldSelectorFixtures.java | 14 ++++++++++++-- ...ublicationOperationPostgresIntegrationTest.java | 6 +++++- ...lmPolicyPublicationPostgresIntegrationTest.java | 5 ++++- ...shAttemptServiceTransactionIntegrationTest.java | 9 +++++++-- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 88161aa7e2..277640b137 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -18,6 +18,7 @@ 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.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -76,6 +77,15 @@ public static WorldPublishedStartLocationEvidence evidence( public static List participants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return participants( + versionId, evidence, AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION); + } + + public static List + participants( + long versionId, + WorldPublishedStartLocationEvidence evidence, + int attestationSchemaVersion) { return net .firedevops .firemud @@ -94,8 +104,8 @@ public static WorldPublishedStartLocationEvidence evidence( "WORLD_MANAGEMENT".equals(owner) ? evidence.request().contentDigest() : "c".repeat(64), - net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .supportedParticipantDigestSchema(owner), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, attestationSchemaVersion), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index 8a7c419329..a2aae7c597 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; @@ -993,7 +994,10 @@ private PublishedReleaseBundle bundle(Fixture fixture) { bundle.setParticipantDigestsJson( new ObjectMapper() .writeValueAsString( - PublishedWorldSelectorFixtures.participants(op.versionId(), op.world()))); + PublishedWorldSelectorFixtures.participants( + op.versionId(), + op.world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))); bundle.setWorldPublishedStartLocationEvidenceJson( new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); return bundle; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 349d624859..2625e24520 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; @@ -699,7 +700,9 @@ private static PublishedReleaseBundle bundle(GameDesignPublicationOperation oper new ObjectMapper() .writeValueAsString( PublishedWorldSelectorFixtures.participants( - operation.versionId(), operation.world()))); + operation.versionId(), + operation.world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))); bundle.setWorldPublishedStartLocationEvidenceJson( new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8)); return bundle; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index c3ea44d6bd..b40081a06a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -14,6 +14,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; @@ -363,7 +364,9 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { invocation -> { VersionDto version = invocation.getArgument(0); return PublishedWorldSelectorFixtures.participants( - version.id(), fixture.operation().world()); + version.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); }); Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) .thenAnswer(invocation -> recordFixtureCandidate(fixture)); @@ -425,7 +428,9 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { candidateVersionId.set(candidate.id()); candidateVersionNumber.set(candidate.versionNumber()); return PublishedWorldSelectorFixtures.participants( - candidate.id(), fixture.operation().world()); + candidate.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { From b447db9c105e9d7ff0edbad0ccec3e04d293ce45 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:51:29 +1300 Subject: [PATCH 18/29] Preserve local peer guard preparation before source convergence --- .../service/impl/GameDesignGrpcService.java | 5 +- .../impl/GameDesignGrpcServiceAuthTest.java | 144 ++++++++++++++++++ .../impl/GameDesignGrpcServiceTest.java | 79 +++++----- 3 files changed, 187 insertions(+), 41 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 34ac490df4..f37bb87919 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -2404,10 +2404,7 @@ private String publishAttemptErrorCode(RuntimeException failure) { } private void requireLaunchAttestationReadAccess() { - if (SessionContext.isInternalService()) { - return; - } - AdminRoleGuard.requireAdminRole(); + requireLaunchDescriptorReadAccess(); } private static UUID canonicalPublicationUuid(String value, String field) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index ecb98ffdfe..a758766cf3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -14,6 +14,9 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; +import net.firedevops.firemud.gamedesign.dto.VersionStateDto; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; @@ -26,6 +29,10 @@ import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; import org.junit.jupiter.api.AfterEach; @@ -159,6 +166,143 @@ public void onCompleted() {} Mockito.verifyNoInteractions(launchDescriptorService); } + @Test + void versionStateAndArtifactStateReadsAllowOnlySameNamespaceGameSessionAndWorldManagementPeers() { + for (String serviceName : List.of("game-session-service", "world-management-service")) { + ReadFixture fixture = readFixture(); + SessionContext.setContext(null, List.of(), Map.of(), true, serviceName, serviceName + "-1"); + withPeer( + serviceName, + "test", + () -> { + AtomicReference versionState = new AtomicReference<>(); + fixture.service.getVersionState( + GetVersionStateRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), + observer(versionState)); + assertEquals("", versionState.get().getError().getCode()); + + AtomicReference artifactState = + new AtomicReference<>(); + fixture.service.getVersionAssetArtifactState( + GetVersionAssetArtifactStateRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + observer(artifactState)); + assertEquals("", artifactState.get().getError().getCode()); + }); + Mockito.verify(fixture.versionService).getVersionState("1", 7L); + Mockito.verify(fixture.artifactService).getState("1", 7L); + SessionContext.clear(); + } + } + + @Test + void versionStateAndArtifactStateReadsDenyWrongPeerNamespaceAndAnonymousCallers() { + for (String[] caller : + new String[][] { + {"account-service", "test"}, + {"game-session-service", "other"}, + {null, "test"} + }) { + ReadFixture fixture = readFixture(); + if (caller[0] != null) { + SessionContext.setContext(null, List.of(), Map.of(), true, caller[0], caller[0] + "-1"); + } + withPeer( + caller[0], + caller[1], + () -> { + AtomicReference versionState = new AtomicReference<>(); + fixture.service.getVersionState( + GetVersionStateRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), + observer(versionState)); + assertEquals("PERMISSION_DENIED", versionState.get().getError().getCode()); + + AtomicReference artifactState = + new AtomicReference<>(); + fixture.service.getVersionAssetArtifactState( + GetVersionAssetArtifactStateRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + observer(artifactState)); + assertEquals("PERMISSION_DENIED", artifactState.get().getError().getCode()); + }); + Mockito.verifyNoInteractions(fixture.versionService, fixture.artifactService); + SessionContext.clear(); + } + } + + private ReadFixture readFixture() { + VersionService versionService = Mockito.mock(VersionService.class); + VersionAssetArtifactService artifactService = Mockito.mock(VersionAssetArtifactService.class); + Mockito.when(versionService.getVersionState("1", 7L)) + .thenReturn( + new VersionStateDto( + "1", 7L, VersionLifecycleState.PUBLISHED, 3L, java.time.LocalDateTime.now())); + Mockito.when(artifactService.getState("1", 7L)) + .thenReturn( + new VersionAssetArtifactStateDto( + "1", + 7L, + 1, + "PUBLISHED", + 2L, + MANIFEST_HASH, + "workflow-1", + null, + null, + java.time.LocalDateTime.now(), + List.of("manifest.json"))); + GameDesignGrpcService service = + new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + versionService, + Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(CompleteLaunchBindingService.class), + Mockito.mock(TemplateRemapSetService.class), + artifactService, + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + return new ReadFixture(service, versionService, artifactService); + } + + private static StreamObserver observer(AtomicReference response) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + + private void withPeer(String serviceName, String namespace, Runnable operation) { + if (serviceName == null) { + operation.run(); + return; + } + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + serviceName) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + + private record ReadFixture( + GameDesignGrpcService service, + VersionService versionService, + VersionAssetArtifactService artifactService) {} + private void underGameSessionPeer(Runnable operation) { GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 35f83c151e..0ba76a4d61 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -1318,24 +1318,28 @@ void getVersionStateReturnsCanonicalStateSnapshot() { LocalDateTime.parse("2026-04-15T12:00:00"))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getVersionState( - GetVersionStateRequest.newBuilder().setTenantId("tenant-1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetVersionStateResponse value) { - ref.set(value); - } + underLaunchPeer( + "game-session-service", + () -> + service.getVersionState( + GetVersionStateRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetVersionStateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + @Override + public void onError(Throwable t) { + throw new AssertionError(t); + } - @Override - public void onCompleted() {} - }); - } + @Override + public void onCompleted() {} + })); assertEquals("", ref.get().getError().getCode()); assertEquals(17L, ref.get().getVersionState().getVersionStateEpoch()); @@ -1483,27 +1487,28 @@ void getVersionAssetArtifactStateReturnsArtifactProof() { List.of("logo.png", "manifest.json"))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getVersionAssetArtifactState( - GetVersionAssetArtifactStateRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetVersionAssetArtifactStateResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> + service.getVersionAssetArtifactState( + GetVersionAssetArtifactStateRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetVersionAssetArtifactStateResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError(t); + } + + @Override + public void onCompleted() {} + })); assertEquals( "ARTIFACT_STATE_PUBLISHED", ref.get().getArtifactState().getArtifactState().name()); From 8f3be450e35832343104a5aff6418ba30298c3e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 06:47:02 +1300 Subject: [PATCH 19/29] test(game-design): use selector v2 participant fixture evidence --- ...PublishedReleaseBundleServiceImplTest.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 0f6cb68a60..6f57a5d2b3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -16,6 +16,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -48,7 +49,9 @@ class PublishedReleaseBundleServiceImplTest { void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() throws Exception { var evidence = selectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); // ISOLATED source-repository response; this test covers service assembly only. when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); @@ -116,7 +119,9 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() throws Exception { var evidence = selectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); assertThatThrownBy( () -> service.createFullVersionBundle( @@ -187,7 +192,10 @@ void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception "publish-workflow", emptyManifest(), "genrev-1", - PublishedWorldSelectorFixtures.participants(7L, evidence), + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); @@ -213,7 +221,10 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() "publish-workflow", emptyManifest(), "genrev-1", - PublishedWorldSelectorFixtures.participants(7L, evidence), + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("selector-ineligible"); @@ -394,7 +405,9 @@ void legacyBundleEntryPointDoesNotReadMutableCommandRevisionRows() { @Test void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Exception { var evidence = selectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) .thenReturn(Optional.of(sourceIdentity())); @@ -469,7 +482,9 @@ private VersionDto version() { @Test void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { var evidence = selectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); when(repository.save(any(PublishedReleaseBundle.class))) @@ -553,7 +568,8 @@ private void assertSelectedCommandsRejected( "publish-workflow", emptyManifest(), "genrev-1", - PublishedWorldSelectorFixtures.participants(7L, evidence), + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), evidence)); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); org.mockito.Mockito.verifyNoInteractions(revisionRepository); From e60415bed7f7337c4914f14517f81efdc2c8d43e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:19:38 +1300 Subject: [PATCH 20/29] Prove selector migration before enforcing publication owner guard --- ...electorSchemaMigrationIntegrationTest.java | 54 ++++++++++++++++--- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java index dff00c3c72..b22e55d32c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -50,14 +50,20 @@ void stopPostgres() { void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws Exception { String schema = newSchema("fresh"); DriverManagerDataSource dataSource = dataSource(schema); - migrate(dataSource, schema, null); + // Exercise the selected-schema guard before V50 requires an operation-backed release insert. + migrate(dataSource, schema, MigrationVersion.fromVersion("49.1")); JdbcTemplate jdbc = new JdbcTemplate(dataSource); PersistedTarget accepted = persistTarget(jdbc, 1); WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); - insertRelease( - jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + long acceptedReleaseId = + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + String acceptedRowBeforeLatest = retainedBundleRow(jdbc, acceptedReleaseId); + Map functionBeforeLatest = selectorFunctionIdentity(jdbc); + Map triggerBeforeLatest = selectorTriggerIdentity(jdbc); + String functionBodyBeforeLatest = selectorFunctionBody(jdbc); PersistedTarget rejected = persistTarget(jdbc, 2); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); @@ -79,6 +85,14 @@ void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws E .isEqualTo("release v2 participant differs from selected commit/digest/schema"); }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + + migrate(dataSource, schema, null); + + assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); + assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBeforeLatest); + assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBeforeLatest); + assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyBeforeLatest); + assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 3); } @Test @@ -106,7 +120,7 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() String functionBodyBefore = selectorFunctionBody(jdbc); assertThat(functionBodyBefore).contains("('GAME_DESIGN_CONTROL_PLANE',1)"); - migrate(dataSource, schema, null); + migrate(dataSource, schema, MigrationVersion.fromVersion("49.1")); assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); assertThat(retainedBundleRow(jdbc, legacyV2BundleId)).isEqualTo(legacyV2RowBefore); @@ -119,9 +133,11 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() PersistedTarget accepted = persistTarget(jdbc, 2); WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); - insertRelease( - jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + long acceptedReleaseId = + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + String acceptedRowBeforeLatest = retainedBundleRow(jdbc, acceptedReleaseId); PersistedTarget rejected = persistTarget(jdbc, 3); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); @@ -143,6 +159,32 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() .isEqualTo("release v2 participant differs from selected commit/digest/schema"); }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + + String functionBodyAfterSelectorMigration = selectorFunctionBody(jdbc); + migrate(dataSource, schema, null); + + assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); + assertThat(retainedBundleRow(jdbc, legacyV2BundleId)).isEqualTo(legacyV2RowBefore); + assertThat(retainedBundleRow(jdbc, acceptedReleaseId)).isEqualTo(acceptedRowBeforeLatest); + assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBefore); + assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBefore); + assertThat(selectorFunctionBody(jdbc)).isEqualTo(functionBodyAfterSelectorMigration); + assertLatestGuardRejectsReleaseWithoutOwnerAttempt(jdbc, 4); + } + + private void assertLatestGuardRejectsReleaseWithoutOwnerAttempt( + JdbcTemplate jdbc, int versionNumber) throws Exception { + // A schema-valid v2 row still needs a genuine publication attempt under the latest guard. + PersistedTarget target = persistTarget(jdbc, versionNumber); + WorldPublishedStartLocationEvidence targetEvidence = evidence(target); + assertThatThrownBy( + () -> + insertRelease( + jdbc, target, targetEvidence, selectedV2Participants(target, targetEvidence))) + .rootCause() + .isInstanceOf(PSQLException.class) + .satisfies(cause -> assertThat(((PSQLException) cause).getSQLState()).isEqualTo("P0002")); + assertThat(releaseCount(jdbc, target.versionId())).isEqualTo(0L); } private DriverManagerDataSource dataSource(String schema) { From 432318f8ca587b6161b2a8a5c746c7405a1d304c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:25:29 +1300 Subject: [PATCH 21/29] Restore coherent conditional publication and retained fixture proof --- .../PublishedReleaseBundleServiceImpl.java | 1 + ...ationOperationPostgresIntegrationTest.java | 6 +- ...emptServiceTransactionIntegrationTest.java | 23 +- .../impl/GameDesignGrpcServiceTest.java | 2 +- ...PublishedReleaseBundleServiceImplTest.java | 7 +- .../VersionPublishCommandServiceImplTest.java | 227 +++++++++++++----- 6 files changed, 188 insertions(+), 78 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 05e1598029..f0551d3cc8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -155,6 +155,7 @@ private PublishedReleaseBundleDto createBundle( toDto(entity); return toDto(repository.save(entity)); } + @Override @Transactional(readOnly = true) public PublishedReleaseBundleDto getPublishedReleaseBundle(String tenantId, long versionId) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index e74add670a..cfb5d7dc30 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -924,7 +924,8 @@ private void publishInTransaction(Fixture fixture, boolean seal) { attempt.setStatus(PublishAttemptStatus.SUCCEEDED); fixture.attempts().save(attempt); if (seal) { - // Emulate the historical V50.6/V50.7 seal storage without querying the V50.9 policy association. + // Emulate the historical V50.6/V50.7 seal storage without querying the V50.9 policy + // association. fixture .operations() .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); @@ -1089,7 +1090,8 @@ private Fixture fixture(String migrationTarget) throws Exception { requested.setName("ISOLATED publication owner"); return games.save(requested); }); - // These V50.6/V50.7 cases model retained history. Insert the canonical owner row before V50.8 so + // These V50.6/V50.7 cases model retained history. Insert the canonical owner row before V50.8 + // so // the current VersionRepository does not enroll it in post-V50.7 source storage. Version version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); var target = diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 30563b4863..30234d4ac4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -1,8 +1,8 @@ package net.firedevops.firemud.gamedesign.service; -import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.io.PrintWriter; import java.io.StringWriter; @@ -22,7 +22,6 @@ import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; -import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; @@ -45,7 +44,6 @@ import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; -import net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; @@ -348,7 +346,6 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); } - @Test void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { String tenantId = "9011"; @@ -524,7 +521,6 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { assertThat(participantCollectionCount).hasValue(2); } - @Test void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed() { String tenantId = "9012"; @@ -600,8 +596,6 @@ void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed .containsExactly(retainedCandidate.getId()); } - - @Test void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { String tenantId = "9013"; @@ -620,7 +614,8 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { assertThat(reconciliationFailure) .isInstanceOf(IllegalStateException.class) - .hasMessage("published release evidence is incomplete; readback/reconciliation is required"); + .hasMessage( + "published release evidence is incomplete; readback/reconciliation is required"); assertThat(reconciliationFailure.getClass().getName()) .isEqualTo( "net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl" @@ -628,9 +623,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); Version retainedDraft = - versionRepository - .findByTenantIdAndId(tenantId, fixture.version().getId()) - .orElseThrow(); + versionRepository.findByTenantIdAndId(tenantId, fixture.version().getId()).orElseThrow(); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); assertThat(attempt.getFailureCode()).isNull(); assertThat(attempt.getFailureMessage()).isNull(); @@ -659,7 +652,6 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { Mockito.anyString()); } - @Test void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() { String tenantId = "9014"; @@ -827,8 +819,7 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate Mockito.anyString(), Mockito.anyString()); Mockito.verify(assetExportService, Mockito.never()) - .deleteExportedAssets( - Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); + .deleteExportedAssets(Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) @@ -1059,8 +1050,7 @@ void selectedMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAnd Mockito.anyString(), Mockito.anyString()); Mockito.verify(assetExportService, Mockito.never()) - .deleteExportedAssets( - Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); + .deleteExportedAssets(Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) @@ -1404,7 +1394,6 @@ private static ExportedAssetManifest exportedManifest() { 1))); } - private long createGameAndPublishedBaseVersion(String tenantId, String gameName) { Game game = new Game(); game.setTenantId(tenantId); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 7fef48e753..19771f2919 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -672,7 +672,7 @@ void publishVersionMapsOwnerProofRefusalToStableApplicationError() throws Except new MutationOwnerProofUnavailableException( "FULL_VERSION_PUBLICATION_UNAVAILABLE", "fresh and pending full-version publication require a production Draft association"); - Mockito.when(versionService.publishVersion("tenant-1", "notes", "request-1")) + Mockito.when(versionService.replayLegacyFullVersion("tenant-1", "notes", "request-1")) .thenThrow(refusal); AtomicReference ref = new AtomicReference<>(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 9dc2387c3f..0d2f1da967 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -109,10 +109,11 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest()); assertThatThrownBy( - () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest())) + () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, logoManifest())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + .hasMessageStartingWith("REPAIR_ATTESTATION_MISMATCH"); } @Test @@ -289,7 +290,6 @@ void legacyFullVersionCannotCreateV1BundleFromMutableRevisions() { org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); } - @Test void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { var refusal = @@ -304,7 +304,6 @@ void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { org.mockito.Mockito.verifyNoInteractions(repository); } - @Test void legacyFullVersionBundleRefusesEmptyManifestBeforeRepositoryAccess() { var refusal = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 08702b935e..ce14f1eca9 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -12,17 +12,20 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; -import java.util.concurrent.atomic.AtomicBoolean; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -1829,7 +1832,6 @@ void freshFullVersionPublishIsDeniedBeforeAnyMutation() { verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } - @Test void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -1864,7 +1866,6 @@ void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } - @Test void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { SelectedPublishFixture fixture = selectedPublishFixture(8); @@ -2016,7 +2017,6 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { publishOrder.verify(publishAttemptRepository).sealPublication(attempt, true); } - @Test void privateMechanicsRecordsTypedPublishGateFailures() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2045,7 +2045,6 @@ void privateMechanicsRecordsTypedPublishGateFailures() { verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } - @Test void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2071,20 +2070,33 @@ void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); } - @Test void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { SelectedPublishFixture fixture = selectedPublishFixture(1); PublishWorkflowRequest request = fixture.request(); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); VersionAssetArtifactStateDto staged = stagedArtifact(request, fixture.version()); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); when(versionAssetArtifactService.findState("tenant-1", 10L)) .thenReturn( Optional.empty(), Optional.of(staged), - Optional.of(staged), - Optional.of(staged), - Optional.of(staged)); + Optional.of(stagedCandidate), + Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(null, manifest, manifest); when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenReturn(staged); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); @@ -2105,9 +2117,20 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - assertTrue(thrown.getMessage().contains("readback/reconciliation is required")); + assertTrue( + thrown.getMessage().contains("exported candidate requires exact retry/reconciliation")); + assertEquals("attestation write outcome is unknown", thrown.getCause().getMessage()); assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService) + .markExportedUnattested( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(10L), + org.mockito.ArgumentMatchers.eq(1), + org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()), + same(manifest)); + verify(versionAssetArtifactService, org.mockito.Mockito.times(4)) + .getExportCandidate("tenant-1", 10L); verify(assetExportService, never()) .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); verify(publishAttemptService, never()) @@ -2116,31 +2139,126 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); } - @Test - void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { + void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Exception { SelectedPublishFixture fixture = selectedPublishFixture(1); - String workflowId = fixture.request().publishWorkflowId(); + SelectionSnapshot seedReservation = fixture.reservation(); + AuthoredDraftPublishSelection seedSelection = seedReservation.selection(); + DraftCommitBinding seedCommit = seedSelection.selectedCommit(); + DraftCommitBinding expandedCommit = + PublishedWorldSelectorFixtures.withIsolatedFreshWorldGraph(seedCommit); + List graphRevisions = new java.util.ArrayList<>(); + for (RevisionPayload revision : expandedCommit.revisions()) { + if (seedCommit.revisions().contains(revision)) continue; + graphRevisions.add( + new RevisionPayload( + Integer.toString(graphRevisions.size()), + revision.revisionId(), + revision.owner(), + revision.payload())); + } + List graphAffectedUnits = + expandedCommit.affectedUnits().stream() + .filter(unit -> !seedCommit.affectedUnits().contains(unit)) + .toList(); + DraftCommitBinding typedCommit = + DraftCommitBinding.create( + seedCommit.target(), + seedCommit.requestId(), + seedCommit.commitId(), + seedCommit.baseCommitId(), + graphRevisions, + graphAffectedUnits); + PublishIntent seedIntent = seedSelection.intent(); + PublishIntent typedIntent = + new PublishIntent( + seedIntent.canonicalTenantId(), + seedIntent.canonicalVersionId(), + seedIntent.publishRequestId(), + seedIntent.expectedVersionStateEpoch(), + seedIntent.notes(), + seedIntent.selectedCommitRequestId(), + seedIntent.selectedCommitId(), + typedCommit.digest()); + VisibilityFence typedFence = + new VisibilityFence( + seedSelection.target(), + seedSelection.fenceRequestId(), + seedSelection.fenceCommitId(), + typedCommit.digest(), + seedSelection.fenceResultVectorJson(), + OffsetDateTime.parse(seedSelection.fenceCreatedAt())); + SelectionSnapshot reservation = + new SelectionSnapshot( + AuthoredDraftPublishSelection.capture( + typedIntent, + seedSelection.target(), + new PublicationEvidence(typedCommit, typedFence)), + seedReservation.createdAt()); + PublishWorkflowRequest request = selectedRequest(reservation); PublishAttempt attempt = fixture.attempt(); + attempt.setRequestDigest(reservation.selection().digest()); Version version = fixture.version(); + fixture = new SelectedPublishFixture(reservation, request, attempt, version); + when(authoredSelections.readByPublishRequest( + typedIntent.canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + String workflowId = request.publishWorkflowId(); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(2L); - List participantDigests = participantDigests(); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + // This fixture stipulates historical Account/APPLIED bytes; it proves no live owner authority. + WorldPublishedStartLocationEvidence fixtureEvidence = + PublishedWorldSelectorFixtures.evidence( + fixture.reservation().selection().target(), + fixture.reservation().selection().selectedCommit()); + WorldPublishedStartLocationEvidence.Request fixtureRequest = fixtureEvidence.request(); + WorldPublishedStartLocationEvidence selectedEvidence = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + fixtureRequest.targetNamespace(), + fixtureRequest.canonicalTenantId(), + fixtureRequest.canonicalVersionId(), + fixtureRequest.intakeRequestId(), + fixtureRequest.publicationFence(), + request.publishRequestId(), + fixtureRequest.requestDigest(), + Long.parseLong(request.intent().expectedVersionStateEpoch()), + workflowId, + fixtureRequest.appliedCommitId(), + fixtureRequest.contentDigest(), + fixtureRequest.digestSchemaVersion(), + fixtureRequest.worldAffectedTuples()), + fixtureEvidence.selectorReceiptBytes(), + fixtureEvidence.originalAccountBindingBytes(), + fixtureEvidence.appliedResultBytes()); + List participantDigests = + PublishedWorldSelectorFixtures.participants( + 10L, selectedEvidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); PublishedReleaseBundleDto bundle = - publishedReleaseBundleDto( + new PublishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, - "v1", + "v2", workflowId, MANIFEST_HASH, List.of("manifest.json"), participantDigests, + List.of(), "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(List.of("manifest.json")), + selectedEvidence); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -2163,10 +2281,10 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); - PublishWorkflowRequest request = - fixture.request(); - PublishWorkflowSnapshot snapshot = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) @@ -2180,10 +2298,6 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { verify(publishAttemptService).markFullVersionSucceeded(workflowId); } - - - - @Test void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2246,8 +2360,7 @@ void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> - reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); assertTrue(thrown.getMessage().contains("candidate/write reconciliation")); assertTrue(possibleObjectWrite.get()); @@ -2269,7 +2382,6 @@ void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @Test void mismatchedPersistedStagedCandidateRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2294,7 +2406,6 @@ void mismatchedPersistedStagedCandidateRemainsPartial() { verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); } - @Test void malformedPersistedStagedCandidateReadbackRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2319,7 +2430,6 @@ void malformedPersistedStagedCandidateReadbackRemainsPartial() { verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); } - @Test void mismatchedStagedArtifactWorkflowRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2340,7 +2450,6 @@ void mismatchedStagedArtifactWorkflowRemainsPartial() { assertSelectedStagedArtifactRemainsPartial(fixture, artifact); } - @Test void mismatchedStagedArtifactScopeRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2361,7 +2470,6 @@ void mismatchedStagedArtifactScopeRemainsPartial() { assertSelectedStagedArtifactRemainsPartial(fixture, artifact); } - @Test void stagedArtifactForPublishedVersionRemainsPartial() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2372,7 +2480,6 @@ void stagedArtifactForPublishedVersionRemainsPartial() { assertSelectedStagedArtifactRemainsPartial(fixture, artifact); } - @Test void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2397,7 +2504,6 @@ void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } - @Test void legacyFullMixedScopeAttemptIsNotRebound() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2420,7 +2526,6 @@ void legacyFullMixedScopeAttemptIsNotRebound() { assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); } - @Test void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2430,19 +2535,6 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup List participantDigests = participantDigests(); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); VersionAssetArtifactStateDto staged = stagedArtifact(request, version); - VersionAssetArtifactStateDto exportedState = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "EXPORTED_UNATTESTED", - 2L, - MANIFEST_HASH, - workflowId, - null, - null, - LocalDateTime.now(), - List.of("manifest.json")); VersionAssetArtifactStateDto stagedCandidate = new VersionAssetArtifactStateDto( "tenant-1", @@ -2473,7 +2565,6 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup LocalDateTime.now()); when(versionAssetArtifactService.findState("tenant-1", 10L)) .thenReturn( - Optional.empty(), Optional.empty(), Optional.of(staged), Optional.of(stagedCandidate), @@ -2500,7 +2591,7 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup 10L, 1, "EXPORTED_UNATTESTED", - 1L, + 3L, MANIFEST_HASH, workflowId, null, @@ -2538,12 +2629,28 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); assertEquals(1L, version.getVersionStateEpoch()); verify(assetExportService).exportAssets("tenant-1", 1); + verify(versionAssetArtifactService) + .markExportedUnattested( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(10L), + org.mockito.ArgumentMatchers.eq(1), + org.mockito.ArgumentMatchers.eq(workflowId), + same(manifest)); verify(versionAssetArtifactService, org.mockito.Mockito.times(4)) .getExportCandidate("tenant-1", 10L); + verify(versionRepository).save(version); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + same(manifest), + any(String.class), + org.mockito.ArgumentMatchers.eq(participantDigests), + same(capturedWorldPublicationEvidence)); verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(publishAttemptRepository, never()) - .sealPublication(fixture.attempt(), org.mockito.ArgumentMatchers.anyBoolean()); + .sealPublication(same(fixture.attempt()), org.mockito.ArgumentMatchers.anyBoolean()); verify(versionAssetArtifactService, never()) .markFailed( any(String.class), @@ -2558,7 +2665,6 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @ParameterizedTest @EnumSource( value = Status.Code.class, @@ -2657,8 +2763,8 @@ private SelectionSnapshot selectedReservation() { AuthoredDraftPublishSelection selection = AuthoredDraftPublishSelection.capture( intent, target, new PublicationEvidence(binding, fence)); - // This is an existing synchronized source selection fixture only. It carries no Account - // authorization or authenticated World publication freeze. + // This fixture selects an existing intent for the private conditional mechanics seam; it + // carries no Account authorization or authenticated World publication freeze. return new SelectionSnapshot(selection, OffsetDateTime.parse("2026-10-08T00:00:00Z")); } @@ -2726,7 +2832,20 @@ private VersionAssetArtifactStateDto stagedArtifact( private PublishWorkflowSnapshot reflectiveUnitHarnessReconcileSelectedPublicationMechanics( PublishWorkflowRequest request) { - return service.reconcileFullVersionPublishMechanics(request); + try { + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileSelectedPublicationMechanics", PublishWorkflowRequest.class); + mechanics.setAccessible(true); + return (PublishWorkflowSnapshot) mechanics.invoke(service, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) throw runtimeException; + if (cause instanceof Error error) throw error; + throw new AssertionError("selected publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("selected publication mechanics harness is unavailable", exception); + } } private Version fullVersion(long versionId, int versionNumber, VersionLifecycleState state) { From 103db4ac95315b739f5375a3f46151450f02f8d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 06:50:48 +1300 Subject: [PATCH 22/29] Record unassigned production read-authority readiness obligations --- .../game-authoring-publishing-and-activation.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 7e89b0699a..3f39bfe800 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -26,6 +26,8 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The current producer captures real committed release-bundle, artifact-state, and version-state projections with the registered source and verifies them before resolving the exact source-bound default-template descriptor. It commits the actual descriptor resolution, independently reads it with its real request/result digests, and rereads source and current owner snapshots before atomically publishing the complete immutable run/project receipt. The capability and receipt bind actual Game Session and World Management leaf certificates to the same CA. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). +The three production read RPCs retain method-specific same-namespace denial before owner access, containing the generic internal-bearer bypass without granting successful read or activation credit. Authorized tenant/scope-bound terminal reads remain unimplemented pending a genuine independently authorized operation-receipt producer, carrier, and verifier for the named Game Session and World Management callers and, for release-bundle reads, Automation & Scripting, as defined by [Version Control](../../architecture/microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state) and [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). The `artifact-read-bearer-trust` and `release-read-tenant-binding` findings remain accepted/open and PR-unassigned production-readiness obligations under the production-readiness-followup decision 1222; they are not fixes in this passive source cut. This tracker update changes neither the #3120 owned source nor production RPC denial, and grants no fix/activation credit or new front prerequisite. + Historical original-source compositional proof was accepted for the bounded World fixture-lifecycle correction at `f330c8721824d063a5eba09afd5388631ae184b9`. The unchanged Java/test/migration parcel at `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` has passing World socket (2), PostgreSQL (3), provider (5), lifecycle unit (22), Game Design production-read denial (4), and producer PostgreSQL (7) cases with no skips. Rebuilt Smoke run `38174536549`, job `114575566943`, tested merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`) after the certificate/configuration repair, passing WebSocket WORLDS/LOGIN/PLAY/LOOK/LOGOUT and Telnet WORLDS/LOGIN/PLAY/LOOK. Focused physical tests and inspected source establish authenticated prepare/activate, exact replay/reconstruction, identity denial, actual opaque reference, and zero denied production-read calls; Smoke corroborates the packaged positive path without individual RPC trace/counter assertions. Startup refusal was skipped; packaged process restart, later protected activation, and hold race/restart proof are not established by this evidence. Earlier private #3151 reconstruction checks are historical evidence for their respective pins only. An earlier Common Platform gate reported 393 passing tests; a later fresh Game Design gate reported 373 passing tests with 61 integration tests skipped; the then-current parent `aeee77d07aa2ec815954c9627308882016ecaf24` reported 305 passing and 52 skipped in 47 seconds. Those results did not validate the merged private asset composition or full runtime. The two World authenticated socket cases passed, while Docker-backed PostgreSQL cases skipped and rebuilt packaged Smoke/restart remained unrun. Historical source proof does not qualify this reconstructed head. The retained `NEW_GAME_ROW` outbox is not delivery or World intake proof, and genuine production producer handoffs remain open; broader capability ratings are unchanged. From 6aaea5ac507dc11fdc2ea97ce804a83588422a65 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:09:21 +1300 Subject: [PATCH 23/29] fix(game-design): protect policy source transitions and publication proof --- .../game-design-service/api-contracts.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 +- ...eDesignDraftTerminalOutcomeRepository.java | 66 +--- .../model/PublishGateFailureCode.java | 3 +- .../GameDesignSourceRepository.java | 11 +- .../RealmPolicyPublicationRepository.java | 32 +- .../publication/RealmPolicySource.java | 12 +- .../RealmPolicySourceRepository.java | 20 +- ...lm_policy_source_head_transition_guard.sql | 97 +++++ ...meDesignSourcePostgresIntegrationTest.java | 39 +- ...lmPolicySourcePostgresIntegrationTest.java | 139 ++++++- ...icyPublicationPostgresIntegrationTest.java | 12 +- ...emptServiceTransactionIntegrationTest.java | 180 +-------- ...PublishedReleaseBundleServiceImplTest.java | 134 +------ .../VersionPublishCommandServiceImplTest.java | 370 ------------------ 15 files changed, 332 insertions(+), 789 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4f9a24bcba..80f87beb8d 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -104,7 +104,7 @@ When Temporal is disabled or its beans are absent, `PublishVersion` has no synch The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). -The published realm-policy owner read is present behind the default-off `firemud.game-design.published-realm-entry-policy-read.enabled` provider. This slice adds only the two `PublishedRealmEntryPolicyService` methods to the base and production bearer-exemption lists; each handler still requires the verified same-namespace Game Session mTLS identity before decoding or owner access. Source and focused test fixtures are present, but final A-dependent compilation, physical PostgreSQL execution, and runtime consumer/activation proof remain unestablished. +The published realm-policy owner read is present behind the default-off `firemud.game-design.published-realm-entry-policy-read.enabled` provider. This slice adds only the two `PublishedRealmEntryPolicyService` methods to the base and production bearer-exemption lists; each handler still requires the verified same-namespace Game Session mTLS identity before decoding or owner access. The provider remains nonactivating and does not supply production Account or World authority. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for the source capability and qualified proof status. ## gRPC APIs diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 7d00b4e66d..46de28354a 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -16,7 +16,7 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; ### Immutable command and realm-policy source -Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The focused source and PostgreSQL test fixtures are present; post-A compilation, focused execution, physical PostgreSQL proof, and runtime-consumer composition remain pending. The read provider remains nonactivating, and its fixtures do not establish production Account or World authority. +Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. Focused source unit, formatting, static, and documentation proof passed on the reconciled source. The review-corrected source passed 472 unit cases and 16 focused PostgreSQL source/publication cases, including additive V50.12 epoch/pointer guards, typed policy-set refusal, seal rollback, and immutable readback. The broader local integration gate remained partial: 17 cases failed on mapped PostgreSQL connection refusal or its context-loading cascade; one stale no-capture expectation was corrected and its four-case suite then passed. The endpoint cause remains unknown, and the full current-candidate integration gate still needs qualification. Runtime-consumer composition and activation remain unproved; prior scoped proof does not establish the current candidate’s complete integration gate. The read provider remains nonactivating, and its fixtures do not establish production Account or World authority. ### Fresh-tenant identity prerequisite @@ -77,7 +77,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate; mapped-endpoint failures remain unqualified. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; latest local PostgreSQL proof has one unresolved mapped-endpoint failure. Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java index d434024b79..ff51060387 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java @@ -46,53 +46,21 @@ GameDesignDraftTerminalOperation claim( Record byOperation = findOperation(operation.accountBinding().operationId(), true); if (byOperation != null) { - GameDesignDraftTerminalOperation persisted = toOperation(byOperation); - requireExactOperation(operation, persisted); - return persisted; - } - Record byCommit = - findOperation(binding.target(), binding.requestId(), binding.commitId(), true); - if (byCommit != null) { - throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( - "A Game Design commit is already claimed by a different Account operation"); + return toOperation(byOperation); } - - Record commit = - dsl.fetchOne( - "SELECT input_digest, binding_json, workflow_state FROM " + if (dsl.fetchOne( + "SELECT 1 FROM " + COMMIT_TABLE + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + "AND request_id = ? AND commit_id = ? FOR UPDATE", binding.target().canonicalTenantId(), binding.target().canonicalVersionId(), binding.requestId(), - binding.commitId()); - if (commit == null) { + binding.commitId()) + == null) { throw new DraftCommitCoordinatorRepository.DraftCommitNotFoundException( "Game Design commit must be claimed before its Account operation"); } - DraftCommitBinding storedBinding = - DraftCommitBinding.fromStored( - commit.get("binding_json", String.class), commit.get("input_digest", String.class)); - requireExactGameDesignBinding(binding, storedBinding); - if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { - throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( - "Original Account operation must be retained before owner dispatch begins"); - } - if (!"DRAFT".equals(lockedVersion.versionState())) { - throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( - "An Account operation can be newly claimed only while its exact Version is DRAFT"); - } - Record slot = - dsl.fetchOne( - "SELECT 1 FROM game_design_draft_commit_application_slot " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - binding.target().canonicalTenantId(), - binding.target().canonicalVersionId()); - if (slot != null) { - throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( - "An Account operation must be claimed before the Version dispatch slot is acquired"); - } DraftAuthorizationFenceBinding account = operation.accountBinding(); dsl.execute( @@ -382,17 +350,16 @@ private GameDesignDraftTerminalOutcome insertOutcome( return retained; } - int inserted = - dsl.execute( - "INSERT INTO " - + OUTCOME_TABLE - + " (operation_id, outcome, owner_result_vector_json, terminal_evidence_bytes, " - + "terminal_evidence_digest) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", - operationId, - result.name(), - ownerResultVectorJson, - finalEvidenceBytes.clone(), - evidenceDigest); + dsl.execute( + "INSERT INTO " + + OUTCOME_TABLE + + " (operation_id, outcome, owner_result_vector_json, terminal_evidence_bytes, " + + "terminal_evidence_digest) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + operationId, + result.name(), + ownerResultVectorJson, + finalEvidenceBytes.clone(), + evidenceDigest); Record persisted = findOutcome(operationId, true); if (persisted == null) { throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( @@ -411,9 +378,6 @@ private GameDesignDraftTerminalOutcome insertOutcome( throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( "Concurrent Game Design terminal result retained different final evidence"); } - if (inserted == 0) { - return retained; - } return retained; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java index 7062b7542a..e4fbe31ab3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java @@ -10,5 +10,6 @@ public enum PublishGateFailureCode { APPLIED_COMMIT_MISMATCH, RECORDED_SCOPE_MISMATCH, RECORDED_DIGEST_SCHEMA_MISMATCH, - RECORDED_CONTENT_DIGEST_MISMATCH + RECORDED_CONTENT_DIGEST_MISMATCH, + INVALID_REALM_ENTRY_POLICY_SET } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index 1281cca507..73885276cd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -17,6 +17,8 @@ import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseEvidence; import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import org.jooq.DSLContext; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -150,7 +152,14 @@ public Capture freeze(GameDesignPublicationOperation operation) { Objects.requireNonNull(operation, "operation"); requireGenesis(operation.account().input().selection().target()); requireReviewed(operation.account().input().selection().selectedCommit()); - RealmPolicySnapshot.Capture policy = policies.freeze(operation); + RealmPolicySnapshot.Capture policy; + try { + policy = policies.freeze(operation); + } catch (RealmPolicySource.InvalidPublicationPolicySetException failure) { + throw new PublishGateFailureException( + PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET, + "A full Version requires 1 through 128 realm policies with exactly one visible public-production realm"); + } CommandSnapshot.Capture command = commands.freeze(operation); Capture result = new Capture(command, policy); Capture retained = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java index 3e160cd10f..cbfb3d6b90 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -7,7 +7,6 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; @@ -17,7 +16,6 @@ import org.jooq.Record; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; /** @@ -37,8 +35,8 @@ public RealmPolicyPublicationRepository(DSLContext dsl) { } /** - * Retains an association only from the operation's actual sealed PUBLISHED owner readback. A - * release with no policy source/capture remains a valid unrelated release and creates no row. + * Retains an association only from the operation's actual sealed PUBLISHED owner readback. Every + * full-Version publication requires its complete frozen policy capture. */ public Optional retainSealedPublished( String publishWorkflowId) { @@ -66,10 +64,7 @@ public Optional retainSealedPublished var sourceRepository = new RealmPolicySourceRepository(dsl); Optional captureResult = sourceRepository.readCapture(operation); if (captureResult.isEmpty()) { - if (sourceExists(target) || selectedCommitDeclaresRealmPolicy(operation)) { - throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); - } - return Optional.empty(); + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); } var capture = captureResult.orElseThrow(); if (!capture.operation().equals(operation) @@ -520,27 +515,6 @@ private void requireActualRelease( } } - private boolean sourceExists(TargetProof target) { - return dsl.fetchExists( - dsl.selectOne() - .from("game_design_realm_policy_source") - .where( - "canonical_tenant_id = ? AND canonical_version_id = ?", - target.canonicalTenantId(), - target.canonicalVersionId())); - } - - private boolean selectedCommitDeclaresRealmPolicy(GameDesignPublicationOperation operation) { - return operation.account().input().selection().selectedCommit().revisions().stream() - .filter(revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) - .anyMatch( - revision -> { - JsonNode root = RealmPolicySource.tree(revision.payload()); - return root.path("revisionKind").isTextual() - && RealmEntryPolicy.REVISION_KIND.equals(root.path("revisionKind").asText()); - }); - } - private void requireExactRetry( RealmPolicyPublishedEvidence.PublishedSet retained, GameDesignPublicationOperation operation, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 504e5cc3e9..47aef963e8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -21,6 +21,12 @@ public final class RealmPolicySource { public static final String SCOPE = "REALM_ENTRY_POLICY_SET"; public static final int MAX_POLICIES = 128; + public static final class InvalidPublicationPolicySetException extends IllegalArgumentException { + InvalidPublicationPolicySetException(String message) { + super(message); + } + } + private RealmPolicySource() {} /** Original authored UUID and logical identity survive every inherited snapshot. */ @@ -80,14 +86,16 @@ public static List effective(List inherited, List update public static List ordered(List policies) { var ordered = draftOrdered(policies); if (policies.isEmpty() || policies.size() > MAX_POLICIES) { - throw new IllegalArgumentException("Complete policy set must contain 1 through 128 policies"); + throw new InvalidPublicationPolicySetException( + "Complete policy set must contain 1 through 128 policies"); } int production = 0; for (Policy policy : policies) { if (policy.policy().visible() && policy.policy().publicProduction()) production++; } if (production != 1) { - throw new IllegalArgumentException("Exactly one visible public-production realm required"); + throw new InvalidPublicationPolicySetException( + "Exactly one visible public-production realm required"); } return ordered; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java index a68f69c8e1..de6a2bcee7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -202,16 +202,6 @@ public RealmPolicyApplication applyMutation(DraftCommitBinding binding) { new BigInteger(epoch).add(BigInteger.ONE).toString(), RealmPolicySource.effective(inheritedPolicies, updates)); var result = new RealmPolicyApplication(genesis, inherited, epoch, snapshot); - int advanced = - dsl.execute( - "UPDATE game_design_realm_policy_source SET source_epoch = ? " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", - snapshot.sourceEpoch(), - binding.target().canonicalTenantId(), - binding.target().canonicalVersionId(), - epoch, - inherited); - if (advanced != 1) throw new IllegalStateException("POLICY_SOURCE_EPOCH_CONFLICT"); dsl.execute( "INSERT INTO game_design_realm_policy_application " + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, genesis_receipt_id, expected_epoch, snapshot_json, result_bytes) " @@ -225,6 +215,16 @@ public RealmPolicyApplication applyMutation(DraftCommitBinding binding) { epoch, snapshot.canonicalJson(), result.canonicalBytes()); + int advanced = + dsl.execute( + "UPDATE game_design_realm_policy_source SET source_epoch = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited); + if (advanced != 1) throw new IllegalStateException("POLICY_SOURCE_EPOCH_CONFLICT"); var retained = application(binding).orElseThrow(); return retained; } diff --git a/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql b/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql new file mode 100644 index 0000000000..f654e77093 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql @@ -0,0 +1,97 @@ +-- Policy source heads have two distinct legal transitions: owner application stages the next +-- epoch while retaining the visible pointer, then synchronized capture advances only the pointer. +-- [jooq ignore start] +CREATE FUNCTION enforce_realm_policy_source_head_transition() RETURNS trigger AS $$ +BEGIN + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_application a + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = a.canonical_tenant_id + AND c.canonical_version_id = a.canonical_version_id + AND c.request_id = a.request_id + AND c.commit_id = a.commit_id + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_version_id = NEW.canonical_version_id + AND a.expected_epoch = OLD.source_epoch + AND a.inherited_commit_id IS NOT DISTINCT FROM OLD.visible_commit_id + AND a.genesis_receipt_id IS NOT DISTINCT FROM OLD.genesis_receipt_id + AND a.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + AND a.snapshot_json::JSONB->>'bindingJson' = c.binding_json + AND a.snapshot_json::JSONB->>'bindingDigest' = c.input_digest + AND (c.binding_json::JSONB->'requiredOwners') @> '["GAME_DESIGN_CONTROL_PLANE"]'::JSONB + AND ( + SELECT count(*) + FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') AS units(unit) + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'REALM_ENTRY_POLICY_SET' + ) = 1 + AND EXISTS ( + SELECT 1 + FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') AS units(unit) + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'REALM_ENTRY_POLICY_SET' + AND unit->>'aggregateId' = NEW.canonical_version_id::TEXT + AND unit->>'scopeType' = 'REALM_ENTRY_POLICY_SET' + AND unit->>'scopeId' = 'effective' + AND unit->>'expectedEpoch' = OLD.source_epoch + ) + AND EXISTS ( + SELECT 1 + FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') AS revisions(revision) + WHERE revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND ((revision->>'payload')::JSONB)->>'revisionKind' = 'REALM_ENTRY_POLICY' + ) + ) THEN + RAISE EXCEPTION 'realm policy source epoch must advance through its exact owner application' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch + OR NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_snapshot s + JOIN game_design_draft_commit_visibility_fence f + ON f.canonical_tenant_id = s.canonical_tenant_id + AND f.canonical_version_id = s.canonical_version_id + AND f.request_id = s.request_id + AND f.commit_id = s.commit_id + JOIN game_design_draft_commit_visibility v + ON v.canonical_tenant_id = f.canonical_tenant_id + AND v.canonical_version_id = f.canonical_version_id + AND v.request_id = f.request_id + AND v.commit_id = f.commit_id + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = f.canonical_tenant_id + AND c.canonical_version_id = f.canonical_version_id + AND c.request_id = f.request_id + AND c.commit_id = f.commit_id + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.commit_id = NEW.visible_commit_id + AND s.inherited_commit_id IS NOT DISTINCT FROM OLD.visible_commit_id + AND s.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + AND s.snapshot_json::JSONB->>'bindingJson' = c.binding_json + AND s.snapshot_json::JSONB->>'bindingDigest' = c.input_digest + AND f.input_digest = c.input_digest + AND v.input_digest = f.input_digest + AND c.workflow_state = 'SYNCHRONIZED' + ) THEN + RAISE EXCEPTION 'realm policy source pointer must advance to its exact current synchronized snapshot' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER realm_policy_source_head_transition_guard + BEFORE UPDATE ON game_design_realm_policy_source + FOR EACH ROW EXECUTE FUNCTION enforce_realm_policy_source_head_transition(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index 019ffb8aa0..2947f823a6 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -15,11 +15,13 @@ import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -179,8 +181,39 @@ void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { } }); assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Exactly one visible public-production realm"); + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET)); + assertThat(fixture.sources().readCapture(operation)).isEmpty(); + } + + @Test + void emptyRealmPolicySourceFailsWithTypedPublicationGateBeforeCapture() { + Fixture fixture = fixture(); + var operation = + fixture.tx( + () -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) + .isInstanceOfSatisfying( + PublishGateFailureException.class, + failure -> + assertThat(failure.failureCode()) + .isEqualTo(PublishGateFailureCode.INVALID_REALM_ENTRY_POLICY_SET)); assertThat(fixture.sources().readCapture(operation)).isEmpty(); } @@ -359,7 +392,7 @@ private static Fixture fixture() { .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") .table("flyway_schema_history_game_design_service") - .target("50.11") + .target("50.12") .load() .migrate(); var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index 3a86f6cf8c..f4a2c6db3b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -254,6 +254,118 @@ void isolatedSiblingSourceComposesOneOwnerResultAndCommandOnlyFenceInheritsPolic }); } + @Test + void sourceHeadRejectsUnprovenTransitionsAndDisjointCaptureInheritsExactPredecessor() { + var fixture = freshFixture(); + var first = policyBinding(fixture.target(), "0", "main", true); + start(fixture, first); + var firstApplication = fixture.tx(() -> fixture.policies().apply(first)); + synchronize(fixture, first, firstApplication); + + var second = policyBinding(fixture.target(), "1", "private", false); + start(fixture, second); + var secondApplication = fixture.tx(() -> fixture.policies().apply(second)); + synchronize(fixture, second, secondApplication); + var current = fixture.reads().readSnapshot(fixture.target(), second.commitId()).orElseThrow(); + assertThat(current.policies()).hasSize(2); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1', visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '4' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source epoch must advance through its exact owner application"); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining( + "realm policy source pointer must advance to its exact current synchronized snapshot"); + + var disjoint = commandOnlyBinding(fixture.target(), second.commitId()); + start(fixture, disjoint); + fixture.tx( + () -> { + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + disjoint.commitId(), + disjoint.digest(), + "ISOLATED-disjoint-command-result", + "ISOLATED command owner readback".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + "COMMAND_DEFINITION_SET", + fixture.target().canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "0", + "1"))); + fixture.coordinator().recordOwnerOutcome(disjoint, outcome); + fixture + .coordinator() + .advanceVisibilityFence( + disjoint, + new DraftCommitCoordinatorRepository.CoordinatorProof( + disjoint, List.of(outcome))); + var inherited = fixture.policies().captureSynchronized(disjoint); + assertThat(inherited.sourceEpoch()).isEqualTo(current.sourceEpoch()); + assertThat(inherited.policies()).containsExactlyElementsOf(current.policies()); + var snapshotRow = + fixture + .dsl() + .fetchOne( + "SELECT inherited_commit_id FROM game_design_realm_policy_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + disjoint.commitId()); + assertThat(snapshotRow).isNotNull(); + assertThat(snapshotRow.get("inherited_commit_id", UUID.class)) + .isEqualTo(second.commitId()); + fixture.coordinator().releaseApplicationSlot(disjoint); + return null; + }); + } + @Test void absentBaselineDeniesAndApplicationReplayAndMismatchBindActualCoordinatorResult() { var fixture = retainedFixture(false); @@ -544,6 +656,29 @@ private static DraftCommitBinding policyBinding( epoch))); } + private static DraftCommitBinding commandOnlyBinding(TargetProof target, UUID baseCommitId) { + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + baseCommitId.toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{\"revisionKind\":\"COMMAND_DEFINITION\",\"schemaVersion\":1," + + "\"operation\":\"DELETE\",\"commandId\":\"ISOLATED-command\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "COMMAND_DEFINITION_SET", + target.canonicalVersionId().toString(), + "COMMAND_DEFINITION_SET", + "effective", + "0"))); + } + private static Fixture freshFixture() { String schema = "gd_policy_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = @@ -557,7 +692,7 @@ private static Fixture freshFixture() { .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") .table("flyway_schema_history_game_design_service") - .target("50.10") + .target("50.12") .load() .migrate(); var transactions = new DataSourceTransactionManager(dataSource); @@ -614,7 +749,7 @@ private static Fixture retainedFixture(boolean isolatedBaseline) { return new GameRepository(dsl).save(created); }); var version = write.execute(status -> insertRetainedVersion(dsl, properties, game, 1)); - migrate(dataSource, schema, "50.10"); + migrate(dataSource, schema, "50.12"); var target = target(version); var baseline = policyBinding(target, "0", "main", true); var policies = new RealmPolicySourceRepository(dsl); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index f29dc84f90..9b8261f25c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -305,16 +305,14 @@ void sealRollbackLeavesNoAssociationAndExactPublicationRetryAllocatesOneStableId } @Test - void releaseWithoutTypedSourceRemainsValidButMissingCaptureWithSourceFailsClosed() - throws Exception { + void missingPolicyCaptureFailsClosedForEveryFullVersionRelease() throws Exception { Fixture unrelated = fixture(false); GameDesignPublicationOperation noPolicy = unrelated.prepare(false); - unrelated.writePublish(noPolicy, false); + assertThatThrownBy(() -> unrelated.writePublish(noPolicy, false)) + .hasMessageContaining("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + assertThat(unrelated.operations().read(noPolicy.workflowId()).orElseThrow().outcome()) + .isEqualTo("PENDING"); assertThat(unrelated.publicationReads().readPublishedSet(unrelated.target())).isEmpty(); - assertThat( - unrelated.tx( - () -> unrelated.publicationWrites().retainSealedPublished(noPolicy.workflowId()))) - .isEmpty(); Fixture missingCapture = fixture(true); GameDesignPublicationOperation policyOperation = missingCapture.prepare(false); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 9b3421dca9..e9d69408f4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -701,7 +701,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { FrozenAssetExportCandidate retainedCandidate = exportCandidateService.readExportCandidate(tenantId, retainedDraft.getVersionNumber()); assertThat(retainedCandidate) - .isEqualTo(new FrozenAssetExportCandidate(candidate, "https://assets.example.test/assets")); + .isEqualTo(new FrozenAssetExportCandidate(candidate, FIXTURE_PUBLIC_BASE_URL)); Mockito.verify(assetExportService) .exportAssets(Mockito.eq(tenantId), Mockito.eq(fixture.version().getVersionNumber())); Mockito.verify(versionAssetArtifactService, Mockito.never()) @@ -945,184 +945,6 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } - @Test - void selectedMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() { - String tenantId = "9003"; - SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "failed-remap-proof-game", true); - String publishRequestId = - fixture.operation().account().input().selection().intent().publishRequestId(); - String publishWorkflowId = fixture.operation().workflowId(); - Version sourceVersion = - versionRepository.findByTenantIdAndVersionNumber(tenantId, 1).orElseThrow(); - long sourceVersionId = sourceVersion.getId(); - AtomicReference candidateVersionId = new AtomicReference<>(); - AtomicReference candidateVersionNumber = new AtomicReference<>(); - AtomicReference exportedVersionNumber = new AtomicReference<>(); - AtomicReference remapSetId = new AtomicReference<>(); - AtomicReference recordedDigestFailure = new AtomicReference<>(); - AtomicReference exportCallbackFailure = new AtomicReference<>(); - AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); - AtomicBoolean exportCompleted = new AtomicBoolean(); - AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); - - Mockito.when( - publishGateService.collectFullVersionParticipantDigests( - Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), - Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto candidate = invocation.getArgument(0); - candidateVersionId.set(candidate.id()); - candidateVersionNumber.set(candidate.versionNumber()); - return PublishedWorldSelectorFixtures.participants( - candidate.id(), - fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); - }); - Mockito.doAnswer( - invocation -> { - try { - invocation.callRealMethod(); - } catch (Throwable failure) { - recordedDigestFailure.set(failure); - throw failure; - } - return null; - }) - .when(recordedParticipantDigestService) - .assertMatchesRecordedDigests( - Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); - ExportedAssetManifest exportedManifest = exportedManifest(); - Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) - .thenAnswer( - invocation -> { - exportedVersionNumber.set(invocation.getArgument(1)); - try { - VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); - approvedRemapSet.setRemapSetId("failed-candidate-approved-remap"); - approvedRemapSet.setTenantId(tenantId); - approvedRemapSet.setSourceVersionId(sourceVersionId); - approvedRemapSet.setTargetVersionId(candidateVersionId.get()); - approvedRemapSet.setStatus(TemplateRemapSetStatus.APPROVED); - approvedRemapSet.setCreatedReason( - "approved remap references publication candidate"); - approvedRemapSet.setApprovalReason("approved for replacement launch"); - approvedRemapSet.setApprovedAt(LocalDateTime.now()); - templateRemapSetRepository.save(approvedRemapSet); - remapSetId.set(approvedRemapSet.getRemapSetId()); - exportCompleted.set(true); - return recordFixtureCandidate(fixture, exportedManifest); - } catch (Throwable failure) { - exportCallbackFailure.set(failure); - throw failure; - } - }); - Mockito.doAnswer( - invocation -> { - finalizationFailureInjected.set(true); - throw new IllegalStateException("forced finalization failure"); - }) - .when(versionAssetArtifactService) - .markPublished( - Mockito.eq(tenantId), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.eq(publishWorkflowId), - Mockito.eq(exportedManifest.manifestHash())); - - Throwable reconciliationFailure = - catchThrowable(() -> reconcileSelectedPublicationMechanics(fixture)); - assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); - assertThat(reconciliationFailure) - .isInstanceOf(IllegalStateException.class) - .hasMessage("exported candidate requires exact retry/reconciliation"); - PublishAttempt attempt = - publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); - String reconciliationContext = - "mechanics reconciliation context (candidateVersionId=" - + candidateVersionId.get() - + ", candidateVersionNumber=" - + candidateVersionNumber.get() - + ", exportedVersionNumber=" - + exportedVersionNumber.get() - + ", attemptStatus=" - + attempt.getStatus() - + ", attemptFailureCode=" - + attempt.getFailureCode() - + ", attemptFailureMessage=" - + attempt.getFailureMessage() - + ", recordedDigestFailure=" - + recordedDigestFailure.get() - + ", exportCallbackFailure=" - + exportCallbackFailure.get() - + ", exportCallbackFailureFrame=" - + firstStackFrame(exportCallbackFailure.get()) - + ", reconciliationFailure=" - + reconciliationFailure - + ")"; - assertThat(exportCompleted.get()).as(reconciliationContext).isTrue(); - assertThat(finalizationFailureInjected.get()).as(reconciliationContext).isTrue(); - assertThat(exportedVersionNumber.get()) - .as("asset export uses the candidate's persisted version number") - .isEqualTo(candidateVersionNumber.get()); - assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); - assertThat(attempt.getFailureCode()).isNull(); - assertThat(attempt.getFailureMessage()).isNull(); - Version retainedCandidate = - versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); - assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); - assertThat(retainedCandidate.getVersionStateEpoch()) - .isEqualTo( - Long.parseLong( - fixture - .operation() - .account() - .input() - .selection() - .intent() - .expectedVersionStateEpoch())); - assertThat( - publishedReleaseBundleRepository.findByTenantIdAndVersionId( - tenantId, candidateVersionId.get())) - .isEmpty(); - VersionAssetArtifact retainedArtifact = - versionAssetArtifactRepository - .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) - .orElseThrow(); - assertThat(retainedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); - FrozenAssetExportCandidate expectedCandidate = - new FrozenAssetExportCandidate(exportedManifest, FIXTURE_PUBLIC_BASE_URL); - assertThat( - exportCandidateService.readExportCandidate( - tenantId, retainedCandidate.getVersionNumber())) - .isEqualTo(expectedCandidate); - assertThat( - exportCandidateService.recordExportCandidate( - tenantId, retainedCandidate.getVersionNumber(), expectedCandidate)) - .isEqualTo(expectedCandidate); - Mockito.verify(versionAssetArtifactService, Mockito.never()) - .markFailed( - Mockito.eq(tenantId), - Mockito.eq(candidateVersionId.get()), - Mockito.eq(candidateVersionNumber.get()), - Mockito.eq(publishWorkflowId), - Mockito.any(ExportedAssetManifest.class), - Mockito.anyString(), - Mockito.anyString()); - Mockito.verify(assetExportService, Mockito.never()) - .deleteExportedAssets(Mockito.eq(tenantId), Mockito.anyInt(), Mockito.anyList()); - VersionTemplateRemapSet retainedRemapSet = - templateRemapSetRepository - .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) - .orElseThrow(); - assertThat(retainedRemapSet.getStatus()).isEqualTo(TemplateRemapSetStatus.APPROVED); - assertThat(retainedRemapSet.getApprovedAt()).isNotNull(); - assertThat(retainedRemapSet.getSourceVersionId()).isEqualTo(sourceVersionId); - assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); - } - @Test void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { String freshTenantId = "9010"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 0d2f1da967..20de82ffc8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -21,11 +21,9 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; -import net.firedevops.firemud.gamedesign.entity.Revision; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; -import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; @@ -40,7 +38,6 @@ class PublishedReleaseBundleServiceImplTest { private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); @Mock private PublishedReleaseBundleRepository repository; - @Mock private RevisionRepository revisionRepository; @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; @@ -77,8 +74,7 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(evidence.canonicalBytes()); assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); - org.mockito.Mockito.verifyNoInteractions(revisionRepository); - org.mockito.Mockito.clearInvocations(versionRepository, revisionRepository, repository); + org.mockito.Mockito.clearInvocations(versionRepository, repository); when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.empty()); var retry = service.createFullVersionBundle( @@ -91,7 +87,7 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe assertEquals(first.id(), retry.id()); assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(first.worldPublishedStartLocationEvidence().canonicalBytes()); - org.mockito.Mockito.verifyNoInteractions(versionRepository, revisionRepository); + org.mockito.Mockito.verifyNoInteractions(versionRepository); org.mockito.Mockito.verify(repository) .requireSelectedCommandDefinitions(any(), any(), any(), any()); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); @@ -201,7 +197,6 @@ void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); - org.mockito.Mockito.verifyNoInteractions(revisionRepository); } @Test @@ -287,35 +282,7 @@ void legacyFullVersionCannotCreateV1BundleFromMutableRevisions() { version(), "workflow-1", logoManifest(), "genrev-1", List.of())) .isInstanceOf(IllegalStateException.class) .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); - org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); - } - - @Test - void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { - var refusal = - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version(), "workflow-1", logoManifest(), "genrev-1", List.of())); - assertEquals( - "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation", - refusal.getMessage()); - org.mockito.Mockito.verifyNoInteractions(repository); - } - - @Test - void legacyFullVersionBundleRefusesEmptyManifestBeforeRepositoryAccess() { - var refusal = - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); - assertEquals( - "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation", - refusal.getMessage()); - org.mockito.Mockito.verifyNoInteractions(repository); + org.mockito.Mockito.verifyNoInteractions(repository, versionRepository); } @Test @@ -364,30 +331,6 @@ private Version sourceIdentity() { return version; } - @Test - void legacyBundleEntryPointRejectsWithoutSelectedPublicationEvidence() { - VersionDto version = - new VersionDto( - 7L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now()); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())) - .isInstanceOf(IllegalStateException.class) - .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); - org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); - } - @Test void retainedBundleWithBlankArtifactDigestStorageKeepsArtifactProofAbsent() { PublishedReleaseBundle retained = new PublishedReleaseBundle(); @@ -458,39 +401,6 @@ void optionalReadDistinguishesMissingBundleWhileRequiredReadStillFails() { () -> service.getPublishedReleaseBundle("tenant-1", 7L)); } - @Test - void legacyBundleEntryPointDoesNotReadMutableCommandRevisionRows() { - VersionDto version = - new VersionDto( - 7L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now()); - Revision first = new Revision(); - first.setData(commandDefinition("salute", "hail")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(first)); - - assertThatThrownBy( - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())) - .isInstanceOf(IllegalStateException.class) - .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); - org.mockito.Mockito.verifyNoInteractions(repository, versionRepository); - org.mockito.Mockito.verify(revisionRepository, org.mockito.Mockito.never()) - .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION"); - } - @Test void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Exception { var evidence = selectorEvidence(); @@ -515,42 +425,6 @@ void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Ex .isInstanceOf(IllegalStateException.class) .hasMessage("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); - org.mockito.Mockito.verifyNoInteractions(revisionRepository); - } - - @Test - void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision first = new Revision(); - first.setData(commandDefinition("salute", "greet")); - Revision second = new Revision(); - second.setData(commandDefinition("hail", "SALUTE")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(first, second)); - - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); - } - - @Test - void legacyFullVersionBundleDoesNotReachMutableCommandValidation() { - VersionDto version = version(); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision commandDefinition = new Revision(); - commandDefinition.setData(validCommandDefinition().replace("\"value\":1", "\"value\":\"one\"")); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(commandDefinition)); - - assertThrows( - IllegalStateException.class, - () -> - service.createFullVersionBundle( - version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } private VersionDto version() { @@ -611,7 +485,6 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); assertThat(dto.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(evidence.canonicalBytes()); - org.mockito.Mockito.verifyNoInteractions(revisionRepository); } @Test @@ -661,7 +534,6 @@ private void assertSelectedCommandsRejected( 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), evidence)); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); - org.mockito.Mockito.verifyNoInteractions(revisionRepository); } private static ExportedAssetManifest emptyManifest() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index ce14f1eca9..0d883874f8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -662,210 +662,6 @@ void mismatchedRequestDigestCannotReplaySucceededAttempt() { verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } - @Test - void reflectiveUnitHarnessReconcilesSelectedExistingVersionWithCapturedOperation() { - SelectedPublishFixture fixture = selectedPublishFixture(8); - Version version = fixture.version(); - PublishWorkflowRequest request = fixture.request(); - PublishAttempt attempt = fixture.attempt(); - List participantDigests = participantDigests(); - ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); - VersionAssetArtifactStateDto staged = stagedArtifact(request, version); - when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.empty(), Optional.of(staged), Optional.of(staged)); - when(versionAssetArtifactService.stageExport("tenant-1", 10L, 8, request.publishWorkflowId())) - .thenReturn(staged); - when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); - when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) - .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); - when(versionAssetArtifactService.markExportedUnattested( - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class), - any(ExportedAssetManifest.class))) - .thenReturn( - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "EXPORTED_UNATTESTED", - 2L, - MANIFEST_HASH, - request.publishWorkflowId(), - null, - null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); - when(publishedReleaseBundleService.createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class), - same(capturedWorldPublicationEvidence))) - .thenReturn( - publishedReleaseBundleDto( - 1L, - "tenant-1", - 10L, - 8, - "v1", - request.publishWorkflowId(), - MANIFEST_HASH, - List.of("logo.png", "manifest.json"), - participantDigests, - "genrev-tenant-1-10", - false, - null, - LocalDateTime.now())); - when(versionAssetArtifactService.markPublished( - any(String.class), - any(Long.class), - any(Long.class), - any(String.class), - any(String.class))) - .thenReturn( - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 8, - "PUBLISHED", - 3L, - MANIFEST_HASH, - request.publishWorkflowId(), - null, - null, - LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); - - PublishWorkflowSnapshot snapshot = - reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); - - assertEquals("SUCCEEDED", snapshot.status()); - assertEquals(10L, snapshot.versionId()); - assertEquals(VersionLifecycleState.PUBLISHED, version.getVersionState()); - assertEquals(2L, version.getVersionStateEpoch()); - verify(versionRepository, never()).findTopByTenantIdOrderByVersionNumberDesc("tenant-1"); - verify(versionRepository).save(version); - verify(publishAttemptService, never()) - .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); - verify(publishAttemptService) - .recordFullVersionParticipantDigests(request.publishWorkflowId(), participantDigests); - verify(publishAttemptRepository).requirePublicationPending(attempt); - verify(publishAttemptRepository).sealPublication(attempt, true); - verify(publishedReleaseBundleService) - .createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class), - same(capturedWorldPublicationEvidence)); - verify(publishedReleaseBundleService, never()) - .createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class)); - - InOrder publishOrder = - inOrder( - publishGateService, - recordedParticipantDigestService, - versionAssetArtifactService, - assetExportService, - publishedReleaseBundleService, - publishAttemptService, - publishAttemptRepository); - publishOrder - .verify(publishGateService) - .assertGatePassed( - any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); - publishOrder - .verify(recordedParticipantDigestService) - .assertMatchesRecordedDigests( - org.mockito.ArgumentMatchers.eq("tenant-1"), - org.mockito.ArgumentMatchers.eq(PublishType.FULL_VERSION), - org.mockito.ArgumentMatchers.eq(participantDigests)); - publishOrder - .verify(versionAssetArtifactService) - .stageExport("tenant-1", 10L, 8, request.publishWorkflowId()); - publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); - publishOrder - .verify(publishAttemptService) - .recordFullVersionParticipantDigests( - org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()), - org.mockito.ArgumentMatchers.eq(participantDigests)); - publishOrder - .verify(publishedReleaseBundleService) - .createFullVersionBundle( - any(VersionDto.class), - any(String.class), - any(ExportedAssetManifest.class), - any(String.class), - any(List.class), - same(capturedWorldPublicationEvidence)); - publishOrder.verify(publishAttemptRepository).sealPublication(attempt, true); - } - - @Test - void publishFullVersionPropagatesTypedPublishGateFailures() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests()); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, - "recorded digest mismatch")) - .when(recordedParticipantDigestService) - .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); - - PublishWorkflowSnapshot snapshot = - reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); - - assertEquals("FAILED", snapshot.status()); - assertEquals( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); - verify(publishAttemptService) - .markFullVersionFailed( - org.mockito.ArgumentMatchers.eq(fixture.request().publishWorkflowId()), - org.mockito.ArgumentMatchers.eq("RECORDED_CONTENT_DIGEST_MISMATCH"), - org.mockito.ArgumentMatchers.eq("recorded digest mismatch")); - verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - - @Test - void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - List participantDigests = participantDigests(); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenReturn(participantDigests); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected")) - .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); - - PublishWorkflowSnapshot snapshot = - reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); - - assertEquals("FAILED", snapshot.status()); - assertEquals( - PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); - verify(publishAttemptService, never()) - .recordFullVersionParticipantDigests(any(String.class), any(List.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - verify(publishAttemptRepository).sealPublication(fixture.attempt(), false); - } - @Test void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2382,150 +2178,6 @@ void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @Test - void mismatchedPersistedStagedCandidateRemainsPartial() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - PublishWorkflowRequest request = fixture.request(); - VersionAssetArtifactStateDto artifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "STAGED", - 2L, - MANIFEST_HASH, - request.publishWorkflowId(), - null, - null, - LocalDateTime.now(), - List.of("manifest.json")); - when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) - .thenReturn(exportedManifest(List.of("different.json"))); - - assertSelectedStagedArtifactRemainsPartial(fixture, artifact); - verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); - } - - @Test - void malformedPersistedStagedCandidateReadbackRemainsPartial() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - PublishWorkflowRequest request = fixture.request(); - VersionAssetArtifactStateDto artifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "STAGED", - 2L, - MANIFEST_HASH, - request.publishWorkflowId(), - null, - null, - LocalDateTime.now(), - List.of("manifest.json")); - when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) - .thenThrow(new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE")); - - assertSelectedStagedArtifactRemainsPartial(fixture, artifact); - verify(versionAssetArtifactService).getExportCandidate("tenant-1", 10L); - } - - @Test - void mismatchedStagedArtifactWorkflowRemainsPartial() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - VersionAssetArtifactStateDto artifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 1, - "STAGED", - 1L, - null, - "other-workflow", - null, - null, - LocalDateTime.now(), - List.of()); - - assertSelectedStagedArtifactRemainsPartial(fixture, artifact); - } - - @Test - void mismatchedStagedArtifactScopeRemainsPartial() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - VersionAssetArtifactStateDto artifact = - new VersionAssetArtifactStateDto( - "tenant-1", - 10L, - 2, - "STAGED", - 1L, - null, - fixture.request().publishWorkflowId(), - null, - null, - LocalDateTime.now(), - List.of()); - - assertSelectedStagedArtifactRemainsPartial(fixture, artifact); - } - - @Test - void stagedArtifactForPublishedVersionRemainsPartial() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - fixture.version().setVersionState(VersionLifecycleState.PUBLISHED); - fixture.version().setVersionStateEpoch(2L); - VersionAssetArtifactStateDto artifact = stagedArtifact(fixture.request(), fixture.version()); - - assertSelectedStagedArtifactRemainsPartial(fixture, artifact); - } - - @Test - void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - PublishWorkflowRequest request = fixture.request(); - PublishAttempt attempt = fixture.attempt(); - Version mismatchedVersion = fullVersion(10L, 2, VersionLifecycleState.DRAFT); - when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) - .thenReturn(Optional.of(mismatchedVersion)); - - assertThrows( - IllegalStateException.class, - () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); - } - - @Test - void legacyFullMixedScopeAttemptIsNotRebound() { - SelectedPublishFixture fixture = selectedPublishFixture(1); - PublishWorkflowRequest request = fixture.request(); - PublishAttempt attempt = fixture.attempt(); - attempt.setBaseVersionId(3L); - - assertThrows( - IllegalStateException.class, - () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); - - verify(publishAttemptRepository, never()) - .backfillFullVersionRequestDigestIfAbsent( - any(Long.class), - any(String.class), - any(String.class), - any(Long.class), - any(Integer.class), - any(String.class)); - assertEquals(fixture.reservation().selection().digest(), attempt.getRequestDigest()); - } - @Test void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2669,28 +2321,6 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup @EnumSource( value = Status.Code.class, names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) - void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { - SelectedPublishFixture fixture = selectedPublishFixture(1); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) - .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); - - VersionPublishCommandServiceImpl.PendingReconciliationException thrown = - assertThrows( - VersionPublishCommandServiceImpl.PendingReconciliationException.class, - () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request())); - - assertTrue(thrown.getMessage().contains("temporarily unavailable")); - assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); - verify(publishAttemptService, never()) - .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); - verify(publishAttemptRepository, never()) - .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); - verify(versionAssetArtifactService, never()) - .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); - verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); - } - private PublishAttempt fullAttempt( PublishAttemptStatus status, long versionId, int versionNumber, String workflowId) { PublishAttempt attempt = new PublishAttempt(); From 00830b1cf8dfdaed29c5a628907136910c06cdd7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:35:23 +1300 Subject: [PATCH 24/29] docs(game-design): retain failed-selection recovery obligation --- .../microservices/game-design-service/version-control.md | 2 ++ .../game-authoring-publishing-and-activation.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 38a308012b..8074e3693e 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -20,6 +20,8 @@ V26's participant-scope and V27's effective-identity migrations are deliberately Current cross-seam security status is also blocked: Account's runtime membership and entitlement gRPC methods are configured as public-method bypasses and their handlers accept caller-supplied account/tenant identifiers without the target exact Game Session or World Management workload policy. Participant digest authorization and tenant-identity gaps are recorded below and remain unproved. +The current passive authored-publication prerequisite retains the first exact selection and does not release its reservation after definitive `FAILED`/`NO_PUBLICATION`. Fresh/PENDING registered ingress is denied before reservation; this containment does not establish failed-selection recovery. The authorized Game Design fresh-attempt or source-bound successor contract and proof remain an OPEN [production-readiness follow-up](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) before selected-publication enablement or genuine protected proof requiring recovery. Preserve immutable original evidence and fresh reviewed bindings; World’s ABORTED reopening after reconciled No Publication is a separate owner boundary. + ## Approach - Each asset revision already stores author and timestamp metadata. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 46de28354a..00c5aaa640 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -26,7 +26,7 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The current producer captures real committed release-bundle, artifact-state, and version-state projections with the registered source and verifies them before resolving the exact source-bound default-template descriptor. It commits the actual descriptor resolution, independently reads it with its real request/result digests, and rereads source and current owner snapshots before atomically publishing the complete immutable run/project receipt. The capability and receipt bind actual Game Session and World Management leaf certificates to the same CA. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). -The three production read RPCs retain method-specific same-namespace denial before owner access, containing the generic internal-bearer bypass without granting successful read or activation credit. Authorized tenant/scope-bound terminal reads remain unimplemented pending a genuine independently authorized operation-receipt producer, carrier, and verifier for the named Game Session and World Management callers and, for release-bundle reads, Automation & Scripting, as defined by [Version Control](../../architecture/microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state) and [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). The `artifact-read-bearer-trust` and `release-read-tenant-binding` findings remain accepted/open and PR-unassigned production-readiness obligations under the production-readiness-followup decision 1222; they are not fixes in this passive source cut. This tracker update changes neither the #3120 owned source nor production RPC denial, and grants no fix/activation credit or new front prerequisite. +The three production read RPCs retain method-specific same-namespace denial before owner access, containing the generic internal-bearer bypass without granting successful read or activation credit. Authorized tenant/scope-bound terminal reads remain unimplemented pending a genuine independently authorized operation-receipt producer, carrier, and verifier for the named Game Session and World Management callers and, for release-bundle reads, Automation & Scripting, as defined by [Version Control](../../architecture/microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state) and [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). The `artifact-read-bearer-trust` and `release-read-tenant-binding` findings remain accepted/open and PR-unassigned production-readiness obligations under the production-readiness-followup decision 1222; they are not fixes in this passive source cut. The Major `failed-selection-recovery` obligation is likewise OPEN and PR-unassigned in that production-readiness follow-up. Game Design retains its immutable first publication selection after definitive `FAILED`/`NO_PUBLICATION`; no authorized fresh-attempt or source-bound successor recovery is implemented or proved. Fresh/PENDING registered publication remains denied before reservation. Before enabling selected publication or claiming genuine protected proof that requires recovery, define and prove the Game Design recovery contract while retaining original selection/terminal evidence and fresh reviewed bindings. World’s accepted ABORTED reopening contract after reconciled No Publication does not itself implement this Game Design boundary. This tracker update changes neither the #3120 owned source nor production RPC denial, and grants no fix/activation credit or new front prerequisite. Historical original-source compositional proof was accepted for the bounded World fixture-lifecycle correction at `f330c8721824d063a5eba09afd5388631ae184b9`. The unchanged Java/test/migration parcel at `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` has passing World socket (2), PostgreSQL (3), provider (5), lifecycle unit (22), Game Design production-read denial (4), and producer PostgreSQL (7) cases with no skips. Rebuilt Smoke run `38174536549`, job `114575566943`, tested merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`) after the certificate/configuration repair, passing WebSocket WORLDS/LOGIN/PLAY/LOOK/LOGOUT and Telnet WORLDS/LOGIN/PLAY/LOOK. Focused physical tests and inspected source establish authenticated prepare/activate, exact replay/reconstruction, identity denial, actual opaque reference, and zero denied production-read calls; Smoke corroborates the packaged positive path without individual RPC trace/counter assertions. Startup refusal was skipped; packaged process restart, later protected activation, and hold race/restart proof are not established by this evidence. From 8a85adf28f9022f59c442de0f4fe87b818e28656 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:04:28 +1300 Subject: [PATCH 25/29] fix(game-design): preserve publication reconciliation and qualify guarded fixtures --- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 2 +- .../game-design/v1/game_design_service.proto | 7 +- .../RealmPolicyPublicationGrpcService.java | 9 +- .../PublishedReleaseBundleRepository.java | 3 - .../VersionPublishCommandServiceImpl.java | 10 +- ...ationOperationPostgresIntegrationTest.java | 44 ++++++- ...icyPublicationPostgresIntegrationTest.java | 115 +++++------------- ...RealmPolicyPublicationGrpcServiceTest.java | 9 ++ .../VersionPublishCommandServiceImplTest.java | 45 ++++++- 10 files changed, 151 insertions(+), 99 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a05b93d5a4..240a291443 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -229,3 +229,9 @@ Entry format: - Context: the shared Gameplay observer monitored a large Validation matrix through `gh run view --json jobs`. - Observation: the returned jobs view omitted failed Buf and Game Logic rows. Their completion timestamps were 01:04:25 and 01:08:08 UTC, but the observer first discovered them around 01:16 UTC through the fully paginated Jobs API; the exact time the API exposed each failure was not recorded. This delayed front-PR failure reporting by roughly 12 and 8 minutes; no GitHub API or FireController failure was established. - Expected pattern: inspect the complete paginated source-run jobs inventory before metadata callbacks and report failed jobs while other jobs remain active. Do not wait for the whole workflow to finish or treat a partial jobs view as exhaustive. + +- `2026-10-13`: Focused validation must use declared test packages and enabled task flags + - Context: Gameplay’s #3120 review-fix prompts assumed that the `unit/` directory prefix was part of every Java package and omitted `-PfullCheck` from static-check tasks. + - Observation: the wrong class filter executed no tests and failed explicitly; the static tasks were reported `SKIPPED` despite a successful focused unit build. Neither result qualified the missing proof. + - Expected pattern: read the class’s declared package before specifying a test filter, and verify task execution rather than equating build success with every requested check passing. Enable the repository’s canonical full-check property when selecting static tasks. + - Current status: corrected package selection passed 50 focused unit cases; the subsequent runtime fix passed 58 selected unit cases. A separate canonical `-PfullCheck` run executed the required static checks successfully. No validation requirement was waived. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 00c5aaa640..aad4dd1356 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -77,7 +77,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate; mapped-endpoint failures remain unqualified. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; latest local PostgreSQL proof has one unresolved mapped-endpoint failure. Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate; The full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures; their cause is unknown. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; The full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures; their cause is unknown. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 57645f99d9..a9eac7b621 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -124,8 +124,11 @@ message PublishVersionRequest { string tenant_id = 1; string notes = 2; string publish_request_id = 3; - // Complete together for new publication: the exact existing Draft selection. - // When all selection fields are empty, only a retained terminal legacy retry is eligible. + // Complete together for new publication: the exact existing Draft selection. When set, + // tenant_id, version_id, selected_commit_request_id, and selected_commit_id must be + // canonical lower-case non-nil UUIDs (tenant_id is the canonical tenant UUID, not the key). + // When all selection fields are empty, tenant_id is the legacy tenant key and only a + // retained terminal legacy retry is eligible. string version_id = 4; string expected_version_state_epoch = 5; string selected_commit_request_id = 6; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java index eaa92ba7dc..9749791c25 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java @@ -17,6 +17,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; /** Protected read adapter; the owner-read opt-in condition controls runtime registration. */ @GrpcService @@ -73,7 +74,9 @@ public void resolvePublishedRealmEntryPolicy( fail(observer, Status.NOT_FOUND, "Published realm policy selector not found"); return; } - } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + } catch (DataAccessException + | org.jooq.exception.DataAccessException + | TransactionException unavailable) { fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); return; } catch (IllegalArgumentException | IllegalStateException inconsistent) { @@ -128,7 +131,9 @@ public void listPublishedRealmEntryPolicies( requireExactTarget( request.canonicalTenantId(), request.canonicalVersionId(), ownerSet.target()); evidence = RealmPolicyPublishedEvidenceMapper.toShared(ownerSet); - } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + } catch (DataAccessException + | org.jooq.exception.DataAccessException + | TransactionException unavailable) { fail(observer, Status.UNAVAILABLE, "Published realm policy owner storage unavailable"); return; } catch (IllegalArgumentException | IllegalStateException inconsistent) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index ce55511cc8..f1bc1c0733 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -302,9 +302,6 @@ private void verifyPersistedSource( || !Objects.equals( persisted.getManifestSchemaVersion(), requested.getManifestSchemaVersion()) || !Objects.equals(persisted.getArtifactDigestsJson(), requested.getArtifactDigestsJson()) - || !Objects.equals( - persisted.getWorldPublishedStartLocationEvidenceJson(), - requested.getWorldPublishedStartLocationEvidenceJson()) || !Objects.equals( persisted.getAttestationSchemaVersion(), requested.getAttestationSchemaVersion()) || !Objects.equals(persisted.getPublishWorkflowId(), requested.getPublishWorkflowId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 2d93e255b9..0408c39596 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -665,7 +665,15 @@ private PublishWorkflowSnapshot failDefinitively( return Boolean.TRUE; }); } catch (PublishAttemptService.FullVersionTransactionException ex) { - PublicationReadback winningPublication = readPublication(request, attempt); + PublicationReadback winningPublication; + try { + winningPublication = readPublication(request, attempt); + } catch (RuntimeException readFailure) { + readFailure.addSuppressed(ex.causeException()); + throw pendingReconciliation( + "full-version failure marking readback failed; reconciliation is required", + readFailure); + } if (winningPublication.isComplete()) return reconcileCommittedAttempt(request, attempt); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index cfb5d7dc30..bfa254ee32 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -839,6 +839,9 @@ void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exce var fixture = fixture(); var sealed = new CountDownLatch(1); var releaseSeal = new CountDownLatch(1); + var attempting = new CountDownLatch(1); + var winnerPid = new AtomicInteger(); + var loserPid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var winner = executor.submit( @@ -848,6 +851,11 @@ void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exce .executeWithoutResult( status -> { noPublicationInTransaction(fixture); + winnerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "no-publication transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); sealed.countDown(); await(releaseSeal); })); @@ -855,9 +863,41 @@ void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exce var loser = executor.submit( () -> { - assertThatThrownBy(() -> publish(fixture)) - .isInstanceOf(IllegalStateException.class); + fixture + .write() + .executeWithoutResult( + status -> { + loserPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "late publisher transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + assertThatThrownBy(() -> publishInTransaction(fixture)) + .isInstanceOf(IllegalStateException.class); + }); }); + assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); + boolean observedBlock = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var activity = + fixture + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' " + + "AND query LIKE 'SELECT id FROM game WHERE tenant_id%' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + winnerPid.get(), loserPid.get()); + if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { + observedBlock = true; + break; + } + Thread.sleep(25); + } + assertThat(observedBlock) + .as("late publisher backend blocked by no-publication winner on the game owner lock") + .isTrue(); releaseSeal.countDown(); winner.get(10, TimeUnit.SECONDS); loser.get(10, TimeUnit.SECONDS); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 9b8261f25c..081516b187 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -12,7 +12,6 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; @@ -27,7 +26,6 @@ import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; -import net.firedevops.firemud.gamedesign.publication.RealmPolicySnapshot; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; @@ -56,7 +54,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.ObjectMapper; -/** Actual Game Design terminal and release rows; the retained policy baseline is ISOLATED. */ +/** Actual Game Design terminal and release rows; the policy author's source input is ISOLATED. */ @Testcontainers(disabledWithoutDocker = true) class RealmPolicyPublicationPostgresIntegrationTest { private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); @@ -175,7 +173,14 @@ void openSetRejectsReplacedSourceAndWrongOrdinalWhileKeepingInheritedProvenance( // A second stipulated ISOLATED owner baseline replaces the main policy. The genuine // publication selection then inherits it through the ordinary frozen-source path. var replacementBinding = - fixture.tx(() -> baseline(fixture.target(), fixture.dsl(), "1", "Replacement World")); + fixture.tx( + () -> + baseline( + fixture.target(), + fixture.dsl(), + fixture.policySource(), + "1", + "Replacement World")); GameDesignPublicationOperation operation = fixture.prepare(true); var selected = fixture.policySource().readCapture(operation).orElseThrow().snapshot(); var replacement = selected.policies().getFirst(); @@ -331,7 +336,7 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); source.setSchema(schema); - migrate(source, schema, "50.7"); + migrate(source, schema, "50.12"); var transactions = new DataSourceTransactionManager(source); var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -342,8 +347,6 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception configuration.set(new SpringTransactionProvider(transactions)); var dsl = DSL.using(configuration); var games = new GameRepository(dsl); - var properties = new PostgresProperties(); - properties.setSchema(schema); var versions = new VersionRepository(dsl); Game game = write.execute( @@ -353,8 +356,14 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception requested.setName("ISOLATED realm policy publication"); return games.save(requested); }); - Version version = write.execute(status -> insertRetainedVersion(dsl, versions, game, 1)); - migrate(source, schema, "50.10"); + Version version = + write.execute( + status -> { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + return versions.save(requested); + }); TargetProof target = new TargetProof( version.getCanonicalTenantId(), @@ -365,7 +374,10 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception version.getIdentitySourceGameTenantKey(), version.getIdentitySourceProvenanceKind()); var policySource = new RealmPolicySourceRepository(dsl); - var baseline = isolatedPolicyBaseline ? write.execute(status -> baseline(target, dsl)) : null; + var baseline = + isolatedPolicyBaseline + ? write.execute(status -> baseline(target, dsl, policySource, "0", "World")) + : null; var publicationWrites = new RealmPolicyPublicationRepository(dsl); var publicationReads = new RealmPolicyPublicationService(publicationWrites, transactions); return new Fixture( @@ -396,87 +408,22 @@ private static void migrate(DriverManagerDataSource source, String schema, Strin .migrate(); } - private static Version insertRetainedVersion( - DSLContext dsl, VersionRepository versions, Game game, int versionNumber) { - var inserted = - dsl.fetchOne( - "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind, version_number, version_state, version_state_epoch, " - + "script_patch_version, base_version_id, is_script_only, notes, created_at, updated_at) " - + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " - + "g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, NULL, NULL, FALSE, " - + "'ISOLATED retained policy publication fixture', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " - + "FROM game g WHERE g.id = ? RETURNING id", - UUID.randomUUID(), - versionNumber, - game.getId()); - if (inserted == null) { - throw new IllegalStateException("ISOLATED retained Game Design owner row is absent"); - } - return versions.findById(inserted.get("id", Long.class)).orElseThrow(); - } - - private static DraftCommitBinding baseline(TargetProof target, DSLContext dsl) { - return baseline(target, dsl, "0", "World"); - } - private static DraftCommitBinding baseline( - TargetProof target, DSLContext dsl, String expectedEpoch, String worldDisplayName) { + TargetProof target, + DSLContext dsl, + RealmPolicySourceRepository policySource, + String expectedEpoch, + String worldDisplayName) { DraftCommitBinding binding = policyBinding(target, expectedEpoch, worldDisplayName); - String sourceEpoch = Long.toString(Long.parseLong(expectedEpoch) + 1); var coordinator = new DraftCommitCoordinatorRepository(dsl); coordinator.claim(binding); coordinator.claimApplicationSlot(binding); coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - binding.commitId(), - binding.digest(), - "ISOLATED-initial-policy-baseline", - "ISOLATED-test-owner-baseline".getBytes(StandardCharsets.UTF_8), - List.of( - new DraftCommitCoordinatorRepository.AppliedEpoch( - RealmPolicySource.SCOPE, - target.canonicalVersionId().toString(), - RealmPolicySource.SCOPE, - "effective", - expectedEpoch, - sourceEpoch))); - coordinator.recordOwnerOutcome(binding, outcome); - IsolatedPublicationOwnerSetup.advanceIsolatedVisibility(dsl, binding, List.of(outcome)); + var applied = policySource.apply(binding); + IsolatedPublicationOwnerSetup.advanceIsolatedVisibility( + dsl, binding, List.of(applied.ownerOutcome())); + policySource.captureSynchronized(binding); coordinator.releaseApplicationSlot(binding); - var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); - var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); - dsl.execute( - "INSERT INTO game_design_realm_policy_snapshot " - + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) " - + "VALUES (?, ?, ?, ?, ?)", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.commitId(), - binding.requestId(), - snapshot.canonicalJson()); - if ("0".equals(expectedEpoch)) { - dsl.execute( - "INSERT INTO game_design_realm_policy_source " - + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) " - + "VALUES (?, ?, ?, ?)", - target.canonicalTenantId(), - target.canonicalVersionId(), - sourceEpoch, - binding.commitId()); - } else { - dsl.execute( - "UPDATE game_design_realm_policy_source SET source_epoch = ?, visible_commit_id = ? " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - sourceEpoch, - binding.commitId(), - target.canonicalTenantId(), - target.canonicalVersionId()); - } return binding; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java index 4cfe2f29fc..61a8caa3d9 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java @@ -175,6 +175,15 @@ void absentOwnerEvidenceUnavailableStorageAndContradictoryEvidenceHaveDistinctSt .thenThrow(new org.jooq.exception.DataAccessException("ISOLATED storage unavailable")); assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) + .thenThrow( + new org.springframework.transaction.CannotCreateTransactionException( + "ISOLATED transaction unavailable")); + assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + var resolve = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest(fixture, "main")); + assertThat(callResolve(handler, resolve, peer).error).isEqualTo(Status.Code.UNAVAILABLE); + verify(owner, org.mockito.Mockito.times(4)).readPublishedSet(any(UUID.class), any(UUID.class)); + when(owner.readPublishedSet(any(UUID.class), any(UUID.class))) .thenThrow(new IllegalStateException("ISOLATED contradictory owner evidence")); assertThat(callList(handler, request, peer).error).isEqualTo(Status.Code.FAILED_PRECONDITION); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 0d883874f8..8d94c4eca8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -1590,6 +1590,47 @@ void preExportFailureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotClean .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } + @Test + void failureMarkingReadbackFailureKeepsPendingContractAndOriginalFailure() { + SelectedPublishFixture fixture = selectedPublishFixture(1); + PublishWorkflowRequest request = fixture.request(); + IllegalStateException operationFailure = new IllegalStateException("failure mark uncertain"); + IllegalStateException readFailure = new IllegalStateException("publication read failed"); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, + "recorded digest mismatch")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.empty()) + .thenThrow(readFailure); + org.mockito.Mockito.doThrow( + new PublishAttemptService.FullVersionTransactionException(operationFailure)) + .when(publishAttemptService) + .executeFullVersionTransaction(any()); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request)); + + assertTrue(thrown.getMessage().contains("failure marking readback failed")); + assertEquals(readFailure, thrown.getCause()); + assertEquals(1, readFailure.getSuppressed().length); + assertEquals(operationFailure, readFailure.getSuppressed()[0]); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + @Test void freshFullVersionPublishIsDeniedBeforeAnyMutation() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -2317,10 +2358,6 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } - @ParameterizedTest - @EnumSource( - value = Status.Code.class, - names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) private PublishAttempt fullAttempt( PublishAttemptStatus status, long versionId, int versionNumber, String workflowId) { PublishAttempt attempt = new PublishAttempt(); From 62af4ca8d003a6cc20569fb962fe9fa809edcaf8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:14:27 +1300 Subject: [PATCH 26/29] docs(game-design): keep integration qualification in one tracker cell --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index aad4dd1356..a74f21f262 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -77,7 +77,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate; The full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures; their cause is unknown. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; The full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures; their cause is unknown. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate: the full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures of unknown cause. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | From 9bf78e22f742c3830821c920e70570eb1bc03e2b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:57:59 +1300 Subject: [PATCH 27/29] Preserve publication receipts and guard Draft visibility advances --- ...ame-authoring-publishing-and-activation.md | 4 +- ...eDesignPublicationOperationRepository.java | 34 ++- ...table_publication_release_row_evidence.sql | 259 ++++++++++++++++++ ..._and_realm_policy_source_insert_guards.sql | 94 +++++++ ...lmPolicySourcePostgresIntegrationTest.java | 212 +++++++++++--- ...ationOperationPostgresIntegrationTest.java | 83 ++++++ ...icyPublicationPostgresIntegrationTest.java | 92 ++++++- ...olicyPublicationReadConfigurationTest.java | 9 +- .../TenantIdentityGrpcAuthWiringTest.java | 7 +- 9 files changed, 746 insertions(+), 48 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index a74f21f262..bd997d68a4 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -16,7 +16,7 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; ### Immutable command and realm-policy source -Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. Focused source unit, formatting, static, and documentation proof passed on the reconciled source. The review-corrected source passed 472 unit cases and 16 focused PostgreSQL source/publication cases, including additive V50.12 epoch/pointer guards, typed policy-set refusal, seal rollback, and immutable readback. The broader local integration gate remained partial: 17 cases failed on mapped PostgreSQL connection refusal or its context-loading cascade; one stale no-capture expectation was corrected and its four-case suite then passed. The endpoint cause remains unknown, and the full current-candidate integration gate still needs qualification. Runtime-consumer composition and activation remain unproved; prior scoped proof does not establish the current candidate’s complete integration gate. The read provider remains nonactivating, and its fixtures do not establish production Account or World authority. +Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. The primary full source run passed 473 unit cases and 109 physical PostgreSQL integration cases with zero skips, including V50.13 stable receipt evidence and V50.14 visibility-pointer and non-genesis source-head guards; the fresh source code and SQL matched that run. After the two nullable-query assertion fixes, the affected 27-case physical PostgreSQL suite passed with zero skips; formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed. The 473 unit result remains current for unchanged unit postimages. An earlier 17-case mapped-endpoint/context-loading failure has an unknown cause and is historical, superseded by the fresh physical PostgreSQL result. Runtime-consumer composition and activation remain unproved. The published-policy provider stays default-off and nonactivating, and its fixtures do not establish production Account or World authority. ### Fresh-tenant identity prerequisite @@ -77,7 +77,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Immutable-source PostgreSQL proof is partial on the latest local parent gate: the full current-candidate integration gate remains unqualified after 17 mapped-endpoint/context-loading failures of unknown cause. Prior proof remains separately qualified: 472 unit tests and 16 focused PostgreSQL cases passed across their respective runs. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. The primary full source run passed 473 unit cases and 109 physical PostgreSQL cases with zero skips. After the two nullable-query assertion fixes, the affected 27-case physical PostgreSQL suite passed with zero skips, and formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed. The earlier 17-case mapped-endpoint/context-loading failure has an unknown cause; it is historical and superseded by the fresh physical PostgreSQL result. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java index 0714337e59..da6f3ddb2f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -16,6 +16,32 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal owner storage collaborator.") public final class GameDesignPublicationOperationRepository { + // Keep this v1 projection fixed: its keys and values reproduce the V50.12 release-row JSON + // byte-for-byte while remaining independent of columns added by later migrations. + private static final String RELEASE_ROW_EVIDENCE_V1 = + "jsonb_build_object(" + + "'artifact_digests_json', r.artifact_digests_json, " + + "'attestation_schema_version', r.attestation_schema_version, " + + "'canonical_tenant_id', r.canonical_tenant_id, " + + "'canonical_version_id', r.canonical_version_id, " + + "'command_definitions_json', r.command_definitions_json, " + + "'generation_config_revision', r.generation_config_revision, " + + "'id', r.id, " + + "'manifest_hash', r.manifest_hash, " + + "'manifest_schema_version', r.manifest_schema_version, " + + "'participant_digests_json', r.participant_digests_json, " + + "'publish_workflow_id', r.publish_workflow_id, " + + "'published_at', r.published_at, " + + "'published_release_bundle_ref', r.published_release_bundle_ref, " + + "'required_manifest_asset_keys_json', r.required_manifest_asset_keys_json, " + + "'script_only', r.script_only, " + + "'script_patch_version', r.script_patch_version, " + + "'tenant_id', r.tenant_id, " + + "'version_id', r.version_id, " + + "'version_number', r.version_number, " + + "'world_published_start_location_evidence_json', r.world_published_start_location_evidence_json" + + ")::TEXT"; + private final DSLContext dsl; public GameDesignPublicationOperationRepository(DSLContext dsl) { @@ -73,7 +99,9 @@ public void seal(String tenant, String workflow, long version, String digest, bo GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); Record release = dsl.fetchOne( - "SELECT r.*, to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + "SELECT r.*, " + + RELEASE_ROW_EVIDENCE_V1 + + " AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", tenant, version); String evidence = release == null ? null : release.get("evidence", String.class); @@ -137,7 +165,9 @@ public Optional read(String workflow) { throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); Record release = dsl.fetchOne( - "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + "SELECT " + + RELEASE_ROW_EVIDENCE_V1 + + " AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", operation.tenantKey(), operation.versionId()); String actual = release == null ? null : release.get("evidence", String.class); diff --git a/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql new file mode 100644 index 0000000000..45dce1c2c4 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql @@ -0,0 +1,259 @@ +-- V1 preserves the exact V50.12 row-JSON bytes while excluding future additive columns. +-- Keep this explicit projection aligned with RELEASE_ROW_EVIDENCE_V1 in +-- GameDesignPublicationOperationRepository. The projection is intentionally not widened. +-- [jooq ignore start] +CREATE FUNCTION publication_release_row_evidence_v1(release_row published_release_bundle) RETURNS TEXT AS $$ + SELECT jsonb_build_object( + 'artifact_digests_json', release_row.artifact_digests_json, + 'attestation_schema_version', release_row.attestation_schema_version, + 'canonical_tenant_id', release_row.canonical_tenant_id, + 'canonical_version_id', release_row.canonical_version_id, + 'command_definitions_json', release_row.command_definitions_json, + 'generation_config_revision', release_row.generation_config_revision, + 'id', release_row.id, + 'manifest_hash', release_row.manifest_hash, + 'manifest_schema_version', release_row.manifest_schema_version, + 'participant_digests_json', release_row.participant_digests_json, + 'publish_workflow_id', release_row.publish_workflow_id, + 'published_at', release_row.published_at, + 'published_release_bundle_ref', release_row.published_release_bundle_ref, + 'required_manifest_asset_keys_json', release_row.required_manifest_asset_keys_json, + 'script_only', release_row.script_only, + 'script_patch_version', release_row.script_patch_version, + 'tenant_id', release_row.tenant_id, + 'version_id', release_row.version_id, + 'version_number', release_row.version_number, + 'world_published_start_location_evidence_json', release_row.world_published_start_location_evidence_json + )::TEXT; +$$ LANGUAGE SQL IMMUTABLE STRICT; + +-- Keep the V50.6 receipt framing and all publication, attempt, and Version gates unchanged. +CREATE OR REPLACE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT publication_release_row_evidence_v1(r) INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +-- Keep the V50.7 terminal framing, closed content projection, and committed-epoch checks unchanged. +CREATE OR REPLACE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR publication_release_row_evidence_v1(release) IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Preserve the complete V50.9 policy-set gate while using the same fixed release-row evidence. +CREATE OR REPLACE FUNCTION guard_published_realm_policy_set() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; owner_game game%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; + capture game_design_realm_policy_capture%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + release published_release_bundle%ROWTYPE; + row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published realm policy set is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.sealed IS DISTINCT FROM FALSE OR NEW.sealed IS DISTINCT FROM TRUE + OR (to_jsonb(NEW) - 'sealed') IS DISTINCT FROM (to_jsonb(OLD) - 'sealed') THEN + RAISE EXCEPTION 'published realm policy set may only be sealed once' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF row_count <> NEW.policy_count + OR row_count <> jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') + OR realm_count <> row_count OR production_count <> 1 + OR NEW.policy_set_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy set is incomplete or has invalid cardinality' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.sealed IS DISTINCT FROM FALSE + OR jsonb_typeof(NEW.target_proof_json::JSONB) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + SELECT count(*) INTO target_proof_key_count + FROM jsonb_object_keys(NEW.target_proof_json::JSONB); + IF target_proof_key_count <> 7 + OR (NEW.target_proof_json::JSONB - ARRAY['canonicalTenantId', 'canonicalVersionId', 'gameDesignVersionRowId', + 'gameDesignVersionTenantKey', 'sourceGameRowId', 'sourceGameTenantKey', 'sourceProvenanceKind']) + IS DISTINCT FROM '{}'::JSONB + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalVersionId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceProvenanceKind') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO owner_version FROM version v JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id::TEXT = NEW.target_proof_json::JSONB->>'sourceGameRowId' + AND v.identity_source_game_tenant_key = NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + AND v.identity_source_provenance_kind = NEW.target_proof_json::JSONB->>'sourceProvenanceKind'; + IF NOT FOUND OR owner_version.id IS DISTINCT FROM NEW.game_design_version_row_id + OR owner_version.version_state IS DISTINCT FROM 'PUBLISHED' + OR owner_version.version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR owner_version.version_number IS DISTINCT FROM NEW.version_number + OR owner_version.is_script_only IS DISTINCT FROM FALSE + OR owner_version.script_patch_version IS NOT NULL + OR owner_version.base_version_id IS NOT NULL + OR NEW.target_proof_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR NEW.target_proof_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.target_proof_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.target_proof_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.target_proof_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'published realm policy set differs from exact full Version owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT g.* INTO STRICT owner_game FROM game g WHERE g.id = owner_version.identity_source_game_row_id; + IF owner_game.id::TEXT IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameRowId' + OR owner_game.tenant_id IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + OR owner_game.tenant_identity_provenance_kind IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceProvenanceKind' + OR owner_game.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id THEN + RAISE EXCEPTION 'published realm policy set source provenance changed' USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set operation is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO capture FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set source capture is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT * INTO release FROM published_release_bundle + WHERE tenant_id = owner_version.tenant_id AND version_id = owner_version.id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set release bundle is unavailable' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome IS DISTINCT FROM 'PUBLISHED' + OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.terminal_evidence_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR operation.release_content_bytes IS DISTINCT FROM NEW.release_content_bytes + OR operation.published_release_bundle_digest IS DISTINCT FROM NEW.published_release_bundle_digest + OR operation.publication_version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR operation.tenant_id IS DISTINCT FROM owner_version.tenant_id + OR operation.version_id IS DISTINCT FROM owner_version.id + OR operation.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR capture.commit_id IS DISTINCT FROM NEW.source_commit_id + OR snapshot.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR publication_release_content(release) IS DISTINCT FROM NEW.release_content_bytes + OR 'sha256:' || encode(sha256(publication_release_content(release)), 'hex') + IS DISTINCT FROM NEW.published_release_bundle_digest + OR release.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR release.version_number IS DISTINCT FROM NEW.version_number + OR release.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR release.manifest_hash IS DISTINCT FROM NEW.manifest_hash + OR publication_release_row_evidence_v1(release) IS DISTINCT FROM operation.release_row_json + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.visible_commit_id = NEW.source_commit_id AND s.source_epoch = NEW.source_epoch) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.commit_id = NEW.source_commit_id) + OR jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') <> NEW.policy_count THEN + RAISE EXCEPTION 'published realm policy set is not bound to exact sealed operation, capture, source, and release' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql b/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql new file mode 100644 index 0000000000..5e8dc75c54 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql @@ -0,0 +1,94 @@ +-- Additive write guards only; retained source rows receive no inferred provenance or rewrite. +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_draft_commit_visibility_pointer_advance() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id THEN + RAISE EXCEPTION 'Game Design Draft visibility pointer target is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.request_id IS NOT DISTINCT FROM OLD.request_id + AND NEW.commit_id IS NOT DISTINCT FROM OLD.commit_id + AND NEW.input_digest IS NOT DISTINCT FROM OLD.input_digest THEN + RETURN NEW; + END IF; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot s + ON s.canonical_tenant_id = c.canonical_tenant_id + AND s.canonical_version_id = c.canonical_version_id + AND s.request_id = c.request_id + AND s.commit_id = c.commit_id + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.request_id + AND c.commit_id = NEW.commit_id + AND c.workflow_state IN ('APPLYING', 'RECONCILIATION_REQUIRED') + ) THEN + RAISE EXCEPTION 'Draft visibility pointer may advance only to its actively applying commit' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_advance + BEFORE INSERT OR UPDATE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_pointer_advance(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_pointer_delete() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design Draft visibility pointers cannot be deleted' + USING ERRCODE = 'check_violation'; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_no_delete + BEFORE DELETE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION reject_gd_draft_commit_visibility_pointer_delete(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_pointer_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_visibility) THEN + RAISE EXCEPTION 'Game Design Draft visibility pointers cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_visibility + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_visibility_pointer_truncate(); + +CREATE FUNCTION enforce_realm_policy_source_head_insert_epoch() RETURNS trigger AS $$ +BEGIN + IF NEW.genesis_receipt_id IS NULL AND NOT EXISTS ( + SELECT 1 + FROM game_design_realm_policy_snapshot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.commit_id = NEW.visible_commit_id + AND s.snapshot_json::JSONB->>'sourceEpoch' = NEW.source_epoch + ) THEN + RAISE EXCEPTION 'realm policy source head must match its visible snapshot epoch' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_realm_policy_source_head_insert_epoch + BEFORE INSERT ON game_design_realm_policy_source + FOR EACH ROW + EXECUTE FUNCTION enforce_realm_policy_source_head_insert_epoch(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index f4a2c6db3b..84189fe07b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -366,6 +366,116 @@ void sourceHeadRejectsUnprovenTransitionsAndDisjointCaptureInheritsExactPredeces }); } + @Test + void nonGenesisSourceHeadInsertRequiresItsVisibleSnapshotEpoch() { + var fixture = retainedFixture(false); + var snapshot = seedRetainedSnapshot(fixture, "1"); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '2', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()))) + .hasMessageContaining("realm policy source head must match its visible snapshot epoch"); + assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_source"))).isZero(); + assertThat( + fixture + .reads() + .readSnapshot(fixture.target(), fixture.baseline().commitId()) + .orElseThrow()) + .isEqualTo(snapshot); + + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()); + return null; + }); + var sourceHead = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT source_epoch FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "valid source-head insert should persist a row"); + assertThat(sourceHead.get("source_epoch", String.class)).isEqualTo("1"); + } + + @Test + void visibilityPointerCannotRewindDeleteOrTruncateAndExactFenceRetryRemainsStable() { + var fixture = freshFixture(); + var first = policyBinding(fixture.target(), "0", "main", true); + start(fixture, first); + var firstApplication = fixture.tx(() -> fixture.policies().apply(first)); + synchronize(fixture, first, firstApplication); + + var second = policyBinding(fixture.target(), "1", "private", false); + start(fixture, second); + var secondApplication = fixture.tx(() -> fixture.policies().apply(second)); + synchronize(fixture, second, secondApplication); + + var replayedFence = + fixture.tx( + () -> + fixture + .coordinator() + .advanceVisibilityFence( + second, + new DraftCommitCoordinatorRepository.CoordinatorProof( + second, List.of(secondApplication.ownerOutcome())))); + assertThat(replayedFence.commitId()).isEqualTo(second.commitId()); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_draft_commit_visibility SET request_id = ?, commit_id = ?, input_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.requestId(), + first.commitId(), + first.digest(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining("may advance only to its actively applying commit"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) + .hasMessageContaining("Draft visibility pointers cannot be deleted"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + + assertThatThrownBy( + () -> + fixture.tx( + () -> fixture.dsl().execute("TRUNCATE game_design_draft_commit_visibility"))) + .hasMessageContaining("Draft visibility pointers cannot be truncated"); + assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); + } + @Test void absentBaselineDeniesAndApplicationReplayAndMismatchBindActualCoordinatorResult() { var fixture = retainedFixture(false); @@ -692,7 +802,7 @@ private static Fixture freshFixture() { .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") .table("flyway_schema_history_game_design_service") - .target("50.12") + .target("50.14") .load() .migrate(); var transactions = new DataSourceTransactionManager(dataSource); @@ -749,7 +859,7 @@ private static Fixture retainedFixture(boolean isolatedBaseline) { return new GameRepository(dsl).save(created); }); var version = write.execute(status -> insertRetainedVersion(dsl, properties, game, 1)); - migrate(dataSource, schema, "50.12"); + migrate(dataSource, schema, "50.13"); var target = target(version); var baseline = policyBinding(target, "0", "main", true); var policies = new RealmPolicySourceRepository(dsl); @@ -764,43 +874,12 @@ private static Fixture retainedFixture(boolean isolatedBaseline) { coordinator, new RealmPolicySourceService(policies, transactions)); if (isolatedBaseline) { + // Historical input for V50.14: this isolated retained-schema fixture is seeded before the + // additive guard migration. Its owner-result bytes are test assumptions, not production + // provenance; V50.14 performs no retained-row provenance inference or rewrite. + seedRetainedSnapshot(fixture, "1"); fixture.tx( () -> { - // Explicit ISOLATED assumption: prior authenticated owner creation supplied this actual - // complete policy source/epoch. There is intentionally no production initializer API. - coordinator.claim(baseline); - coordinator.claimApplicationSlot(baseline); - coordinator.markOwnerInProgress(baseline, Owner.GAME_DESIGN_CONTROL_PLANE); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - baseline.commitId(), - baseline.digest(), - "ISOLATED-initial-owner-baseline", - "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), - List.of( - new DraftCommitCoordinatorRepository.AppliedEpoch( - RealmPolicySource.SCOPE, - target.canonicalVersionId().toString(), - RealmPolicySource.SCOPE, - "effective", - "0", - BigInteger.ONE.toString()))); - coordinator.recordOwnerOutcome(baseline, outcome); - coordinator.advanceVisibilityFence( - baseline, - new DraftCommitCoordinatorRepository.CoordinatorProof(baseline, List.of(outcome))); - coordinator.releaseApplicationSlot(baseline); - var policy = RealmPolicySource.revision(baseline, baseline.revisions().getFirst()); - var snapshot = new RealmPolicySnapshot(baseline, "1", List.of(policy)); - dsl.execute( - "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", - target.canonicalTenantId(), - target.canonicalVersionId(), - baseline.commitId(), - baseline.requestId(), - snapshot.canonicalJson()); dsl.execute( "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", target.canonicalTenantId(), @@ -809,9 +888,68 @@ private static Fixture retainedFixture(boolean isolatedBaseline) { return null; }); } + migrate(dataSource, schema, "50.14"); return fixture; } + private static RealmPolicySnapshot seedRetainedSnapshot(Fixture fixture, String sourceEpoch) { + return fixture.tx( + () -> { + var binding = fixture.baseline(); + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-initial-owner-baseline", + "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + BigInteger.ONE.toString()))); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + fixture.coordinator().releaseApplicationSlot(binding); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + snapshot.canonicalJson()); + return snapshot; + }); + } + + private static UUID visiblePointerCommit(Fixture fixture) { + var pointer = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT commit_id FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()), + "synchronized Draft commit should retain its visibility pointer"); + return pointer.get("commit_id", UUID.class); + } + private static void migrate(DriverManagerDataSource dataSource, String schema, String target) { Flyway.configure() .dataSource(dataSource) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index bfa254ee32..61db868320 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -544,6 +544,89 @@ void retainedV50_6TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch .isNull(); } + @Test + void publicationReceiptSurvivesAdditiveReleaseColumnAndFreshSealAfterAddition() throws Exception { + var retained = fixture(); + publish(retained); + var original = retained.service().readExact(retained.operation()).orElseThrow(); + String originalEvidence = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT release_row_json FROM game_design_publication_operation WHERE publish_workflow_id = ?", + retained.operation().workflowId()), + "Expected retained publication operation row") + .get("release_row_json", String.class); + String originalWholeRow = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()), + "Expected original published release row") + .get("evidence", String.class); + assertThat(originalEvidence).isEqualTo(originalWholeRow); + + retained.completeMigration().run(); + retained + .write() + .executeWithoutResult( + status -> + retained + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + String expandedWholeRow = + java.util.Objects.requireNonNull( + retained + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()), + "Expected published release row after additive column") + .get("evidence", String.class); + assertThat(expandedWholeRow).isNotEqualTo(originalEvidence); + var replay = retained.service().readExact(retained.operation()).orElseThrow(); + assertThat(replay.receiptBytes()).isEqualTo(original.receiptBytes()); + assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); + assertThatThrownBy( + () -> + retained + .write() + .executeWithoutResult( + status -> + retained + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()))) + .isInstanceOf(RuntimeException.class); + assertThat(retained.service().readExact(retained.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + + var fresh = fixture(); + fresh.completeMigration().run(); + fresh + .write() + .executeWithoutResult( + status -> + fresh + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + publish(fresh); + var freshRead = fresh.service().readExact(fresh.operation()).orElseThrow(); + assertThat(freshRead.outcome()).isEqualTo("PUBLISHED"); + assertThat(freshRead.receiptBytes()).isNotNull(); + assertThat(fresh.service().readExact(fresh.operation()).orElseThrow().receiptBytes()) + .isEqualTo(freshRead.receiptBytes()); + } + private ReadCollector readThroughHandler( Fixture fixture, GameDesignPublicationTerminalReadEvidence.ReadRequest request, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 081516b187..7f5019e0b5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -84,12 +84,57 @@ class RealmPolicyPublicationPostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); @Test - void actualSealAssociatesCompleteSetAndReadKeepsOriginalEpochAfterVersionMovement() - throws Exception { + void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exception { Fixture fixture = fixture(true); GameDesignPublicationOperation operation = fixture.prepare(true); fixture.writePublish(operation, false); + var originalOwnerRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + String originalReleaseEvidence = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT release_row_json FROM game_design_publication_operation WHERE publish_workflow_id = ?", + operation.workflowId()), + "Expected retained policy publication operation row") + .get("release_row_json", String.class); + String originalWholeReleaseRow = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()), + "Expected original policy published release row") + .get("evidence", String.class); + assertThat(originalReleaseEvidence).isEqualTo(originalWholeReleaseRow); + + fixture.tx( + () -> { + fixture + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); + String expandedWholeReleaseRow = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()), + "Expected policy published release row after additive column") + .get("evidence", String.class); + assertThat(expandedWholeReleaseRow).isNotEqualTo(originalReleaseEvidence); + var retainedOwnerRead = fixture.operations().read(operation.workflowId()).orElseThrow(); + assertThat(retainedOwnerRead.receiptBytes()).isEqualTo(originalOwnerRead.receiptBytes()); + assertThat(retainedOwnerRead.terminalEvidenceBytes()) + .isEqualTo(originalOwnerRead.terminalEvidenceBytes()); + var original = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); assertThat(original.policies()).hasSize(1); assertThat(original.policyCount()).isEqualTo(1); @@ -157,6 +202,47 @@ void actualSealAssociatesCompleteSetAndReadKeepsOriginalEpochAfterVersionMovemen fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()))) .isInstanceOf(RuntimeException.class); + + Fixture fresh = fixture(true); + fresh.tx( + () -> { + fresh + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); + GameDesignPublicationOperation freshOperation = fresh.prepare(true); + fresh.writePublish(freshOperation, false); + var freshRead = fresh.publicationReads().readPublishedSet(fresh.target()).orElseThrow(); + assertThat(freshRead.policies()).hasSize(1); + assertThat(freshRead.policyCount()).isEqualTo(1); + assertThat( + fresh + .publicationReads() + .readPublishedPolicy(fresh.target(), "world", "main") + .orElseThrow() + .policyId()) + .isEqualTo(freshRead.policies().getFirst().policyId()); + var freshOwnerRead = fresh.operations().read(freshOperation.workflowId()).orElseThrow(); + assertThat(freshOwnerRead.outcome()).isEqualTo("PUBLISHED"); + byte[] freshReceipt = freshOwnerRead.receiptBytes(); + assertThat(freshReceipt).isNotNull(); + var freshRetry = + fresh.tx( + () -> + fresh + .publicationWrites() + .retainSealedPublished(freshOperation.workflowId()) + .orElseThrow()); + assertThat(freshRetry.policies().getFirst().policyId()) + .isEqualTo(freshRead.policies().getFirst().policyId()); + assertThat(freshRetry.operationBytes()).containsExactly(freshRead.operationBytes()); + assertThat(freshRetry.captureBytes()).containsExactly(freshRead.captureBytes()); + assertThat(freshRetry.terminalEvidenceBytes()) + .containsExactly(freshRead.terminalEvidenceBytes()); + assertThat(fresh.operations().read(freshOperation.workflowId()).orElseThrow().receiptBytes()) + .isEqualTo(freshReceipt); } @Test @@ -336,7 +422,7 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); source.setSchema(schema); - migrate(source, schema, "50.12"); + migrate(source, schema, "50.14"); var transactions = new DataSourceTransactionManager(source); var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index a68ad48040..4ab73cfb74 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Bindable; @@ -88,7 +89,11 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept .orElse(List.of())) .containsExactly( "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", - "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", - "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies")); + PublishedRealmEntryPolicyServiceGrpc + .getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc + .getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName())); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index c0507bdcc0..94bce5de72 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import org.junit.jupiter.api.Test; @@ -54,8 +55,10 @@ class TenantIdentityGrpcAuthWiringTest { private static final List CONFIGURED_PUBLIC_METHODS = List.of( FRESH_CREATION_METHOD, - "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", - "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies"); + PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName()); private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; From 915227756111c4a227ce4d6a0d7c487ec308f1d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:46:53 +1300 Subject: [PATCH 28/29] Fix selected terminal replay and qualify current-schema publication proof --- ...ame-authoring-publishing-and-activation.md | 6 +- .../VersionPublishCommandServiceImpl.java | 30 +- .../draft/IsolatedPublicationOwnerSetup.java | 28 ++ ...meDesignSourcePostgresIntegrationTest.java | 4 +- ...lmPolicySourcePostgresIntegrationTest.java | 4 +- ...icyPublicationPostgresIntegrationTest.java | 113 +++++-- .../publication/CommandSourceTest.java | 26 +- .../VersionPublishCommandServiceImplTest.java | 287 ++++++++++++++++++ 8 files changed, 444 insertions(+), 54 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 19a00cb4d7..e051361f2f 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -12,6 +12,8 @@ The published #3120 immutable-source proof checkpoint is `9bf78e22f742c3830821c9 The subsequent combined #3120 CLI5/Hosted3 fixes were validated locally before publication, based on `9bf78e22f742c3830821c920e70570eb1bc03e2b` plus develop `ee0c4c9545af05fa8d69644e78a99ea7c7031fe9`. The 2026-10-13 07:04–07:08 UTC full Game Design run executed 476 unit and 114 physical PostgreSQL cases with zero skips; one rollback assertion retained the old empty-table expectation despite the new legitimate baseline application. After correcting that assertion to prove the mutation row absent and the baseline retained, the 07:09–07:11 UTC affected 12-case PostgreSQL run passed with zero failures, errors or skips. Actual jOOQ generation, formatting, fullCheck, Checkstyle and all three SpotBugs tasks passed. These results qualify the inspected local fix postimages, not a later candidate or packaged runtime; historical container endpoint failures remain unexplained. +The subsequent CLI6/Hosted4 correction batch passed local proof on 2026-10-13: 483 unit cases and 114 physical PostgreSQL cases with zero failures, errors or skips, using the shared pinned PostgreSQL image. Selected successful publication replay accepts exact committed evidence after PUBLISHED, ACTIVE or RETIRED without publication writes; mismatched bundle, artifact, gate and recorded digest remain denied. The policy publication fixture exercises the latest schema and exact authored source base. Formatting, fullCheck, Checkstyle, all three SpotBugs tasks, link checking, Markdown lint and the 79-leaf capability-tracking check passed. These results qualify the inspected source postimages; rebuilt packaged runtime on this correction batch remains unrun. + This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. @@ -20,7 +22,7 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; ### Immutable command and realm-policy source -Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. The source proof checkpoint was locally unpublished at execution and matches postimages at `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary proof log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` covers 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on the matching postimages; this is not a run on a later HEAD. The V50.15 required-owner guard and exact publication-terminal denial assertions are pending consolidated proof. Runtime-consumer composition and activation remain unproved. The published-policy provider stays default-off and nonactivating, and its fixtures do not establish production Account or World authority. +Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewed-base evidence, and a durable publication-operation terminal seal. The two published-policy owner-read RPCs are registered behind the default-off provider flag and require the exact same-namespace Game Session workload identity. The inherited published-policy proto and Common Platform Core codec/evidence dependency is present and compiled. The historical published source proof checkpoint is `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary proof log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` covers 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on the matching postimages; this is not a run on a later HEAD. The subsequent combined local proof described above covers the V50.15 required-owner guard and exact publication-terminal denial assertions. Current-head source Validation `38361682862` (job `115177242916`, tested merge `c86f319c6e205e3c3b6a84b3915f144261470394`) independently executed 476 unit and 114 physical PostgreSQL cases with zero failures, errors or skips on published `3e8126217206419bc379497988884739a8e1fda0`. Runtime-consumer composition and activation remain unproved. The published-policy provider stays default-off and nonactivating, and its fixtures do not establish production Account or World authority. ### Fresh-tenant identity prerequisite @@ -81,7 +83,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Prior source proof on locally unpublished postimages matching `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The V50.15 owner-list guard and exact publication-terminal denial assertions are pending consolidated proof. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index cc51a94013..b75f335bc1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -413,12 +413,12 @@ private PublishWorkflowSnapshot finalizeFullVersion( validateFullVersionAttempt(attempt, request); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { publishAttemptRepository.requirePublishedOperation(attempt); - PublicationReadback readback = readPublication(request, attempt); + PublicationReadback readback = readPublication(request, attempt, true); if (!readback.isComplete()) { throw pendingReconciliation( "succeeded full-version attempt lacks exact committed release evidence"); } - assertCommittedBundleMayMarkSuccess(request, readback); + assertCommittedBundleEvidence(request, readback); return succeededSnapshot(attempt); } if (attempt.getStatus() != PublishAttemptStatus.PENDING) { @@ -430,7 +430,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( Version version = requireAttemptVersionForUpdate(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); if (existingPublication.isComplete()) { - assertCommittedBundleMayMarkSuccess(request, existingPublication); + assertCommittedBundleEvidence(request, existingPublication); recordedParticipantDigestService.recordVerifiedDigests( request.tenantId(), PublishType.FULL_VERSION, @@ -518,7 +518,7 @@ private PublishWorkflowSnapshot replaySucceededAttempt( try { requireExactCommittedBundleIdentity(request, attempt, bundle); if (request.intent() != null) { - assertCommittedBundleMayMarkSuccess(request, readPublication(request, attempt)); + assertCommittedBundleEvidence(request, readPublication(request, attempt, true)); } } catch (RuntimeException ex) { throw pendingReconciliation( @@ -559,7 +559,7 @@ private void recordVerifiedAndSucceed( if (!Objects.equals(bundle, currentReadback.bundle())) { throw pendingReconciliation("published release bundle changed during reconciliation"); } - assertCommittedBundleMayMarkSuccess(request, currentReadback); + assertCommittedBundleEvidence(request, currentReadback); recordedParticipantDigestService.recordVerifiedDigests( request.tenantId(), PublishType.FULL_VERSION, @@ -580,15 +580,14 @@ private void recordVerifiedAndSucceed( } /** - * Revalidates durable publication evidence before it can bless an attempt as successful. + * Revalidates retained publication evidence against the same gate used before first success. * *

Readback proves that the bundle and artifact are structurally tied to this attempt, but it * does not by itself prove that the participant matrix, typed scope, digest schema/content, and - * recorded baseline still satisfy the canonical publication gate. Reconciliation must apply the - * same local contracts as the initial publication path and fail closed for malformed or legacy - * evidence. + * recorded baseline still satisfy the canonical publication gate. Malformed or legacy evidence + * still fails closed. This read does not renew publication authority or mutate lifecycle state. */ - private void assertCommittedBundleMayMarkSuccess( + private void assertCommittedBundleEvidence( PublishWorkflowRequest request, PublicationReadback readback) { if (!readback.isComplete() || readback.version() == null || readback.bundle() == null) { throw pendingReconciliation( @@ -778,6 +777,11 @@ private Version requireAttemptVersionForUpdate( private PublicationReadback readPublication( PublishWorkflowRequest request, PublishAttempt attempt) { + return readPublication(request, attempt, false); + } + + private PublicationReadback readPublication( + PublishWorkflowRequest request, PublishAttempt attempt, boolean terminalReplay) { Optional version = versionRepository.findByTenantIdAndId(request.tenantId(), attempt.getVersionId()); if (version.isEmpty()) { @@ -813,7 +817,11 @@ private PublicationReadback readPublication( } catch (RuntimeException ex) { return PublicationReadback.partial(); } - if (version.get().getVersionState() != VersionLifecycleState.PUBLISHED) { + VersionLifecycleState state = version.get().getVersionState(); + boolean retainedTerminalState = + terminalReplay + && (state == VersionLifecycleState.ACTIVE || state == VersionLifecycleState.RETIRED); + if (state != VersionLifecycleState.PUBLISHED && !retainedTerminalState) { return PublicationReadback.partial(); } return PublicationReadback.complete(version.get(), bundle, artifact); diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 00fa500acc..f67705e9f7 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -2,6 +2,7 @@ import java.math.BigInteger; import java.util.List; +import java.util.Objects; import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftBaseReference; @@ -44,6 +45,16 @@ public static void advanceIsolatedVisibility( binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); } + /** Actual joined source captures; supplied remote owner authority remains explicitly isolated. */ + public static void advanceIsolatedSourceVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceSourceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + /** * Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. */ @@ -71,6 +82,23 @@ public static GameDesignPublicationOperation retainSourceBacked( return retain(dsl, target, draftEpoch, notes, true); } + /** Resolve and retain the exact current authored or genesis source base for this fixture. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + String sourceBaseReference) + throws Exception { + return retain( + dsl, + target, + draftEpoch, + notes, + true, + Objects.requireNonNull(sourceBaseReference, "sourceBaseReference")); + } + /** * Finalizer-only fixture: author a complete minimal policy, select a later World-only commit, and * freeze both exact selected source captures in the caller-owned owner transaction. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index 3cb1c5fd52..d9094132da 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -42,7 +43,8 @@ @Testcontainers(disabledWithoutDocker = true) class GameDesignSourcePostgresIntegrationTest { @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index 5e87f0d900..1f02c6a541 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceService; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -51,7 +52,8 @@ @Testcontainers(disabledWithoutDocker = true) class RealmPolicySourcePostgresIntegrationTest { @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 7f5019e0b5..51996e07c8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -9,6 +9,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftBaseReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; @@ -16,6 +17,7 @@ import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -23,6 +25,7 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; @@ -33,6 +36,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.ExecuteContext; @@ -81,7 +85,8 @@ class RealmPolicyPublicationPostgresIntegrationTest { "sealed"); @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exception { @@ -264,8 +269,7 @@ void openSetRejectsReplacedSourceAndWrongOrdinalWhileKeepingInheritedProvenance( baseline( fixture.target(), fixture.dsl(), - fixture.policySource(), - "1", + new GameDesignSourceRepository(fixture.dsl()), "Replacement World")); GameDesignPublicationOperation operation = fixture.prepare(true); var selected = fixture.policySource().readCapture(operation).orElseThrow().snapshot(); @@ -422,7 +426,7 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); source.setSchema(schema); - migrate(source, schema, "50.14"); + migrate(source, schema); var transactions = new DataSourceTransactionManager(source); var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -432,6 +436,8 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(source))); configuration.set(new SpringTransactionProvider(transactions)); var dsl = DSL.using(configuration); + var sources = new GameDesignSourceRepository(dsl); + var policySource = new RealmPolicySourceRepository(dsl); var games = new GameRepository(dsl); var versions = new VersionRepository(dsl); Game game = @@ -448,21 +454,17 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception var requested = new Version(); requested.setTenantId(game.getTenantId()); requested.setVersionNumber(1); - return versions.save(requested); + Version created = versions.save(requested); + sources + .readGenesis(target(created)) + .orElseThrow( + () -> new IllegalStateException("fresh Version lacks actual source genesis")); + return created; }); - TargetProof target = - new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); - var policySource = new RealmPolicySourceRepository(dsl); + TargetProof target = target(version); var baseline = isolatedPolicyBaseline - ? write.execute(status -> baseline(target, dsl, policySource, "0", "World")) + ? write.execute(status -> baseline(target, dsl, sources, "World")) : null; var publicationWrites = new RealmPolicyPublicationRepository(dsl); var publicationReads = new RealmPolicyPublicationService(publicationWrites, transactions); @@ -481,7 +483,7 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception publicationReads); } - private static void migrate(DriverManagerDataSource source, String schema, String target) { + private static void migrate(DriverManagerDataSource source, String schema) { Flyway.configure() .dataSource(source) .schemas(schema) @@ -489,7 +491,6 @@ private static void migrate(DriverManagerDataSource source, String schema, Strin .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") .table("flyway_schema_history_game_design_service") - .target(target) .load() .migrate(); } @@ -497,24 +498,27 @@ private static void migrate(DriverManagerDataSource source, String schema, Strin private static DraftCommitBinding baseline( TargetProof target, DSLContext dsl, - RealmPolicySourceRepository policySource, - String expectedEpoch, + GameDesignSourceRepository sources, String worldDisplayName) { - DraftCommitBinding binding = policyBinding(target, expectedEpoch, worldDisplayName); + SourceHead head = currentSourceHead(target, dsl, sources); + DraftCommitBinding binding = + policyBinding(target, head.baseReference(), head.sourceEpoch(), worldDisplayName); var coordinator = new DraftCommitCoordinatorRepository(dsl); - coordinator.claim(binding); + var reviewed = + new GameDesignReviewedBaseRepository(dsl) + .resolve(target, DraftBaseReference.parse(binding.baseCommitId())); + sources.claimReviewed(binding, reviewed); coordinator.claimApplicationSlot(binding); coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = policySource.apply(binding); - IsolatedPublicationOwnerSetup.advanceIsolatedVisibility( + var applied = sources.apply(binding); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( dsl, binding, List.of(applied.ownerOutcome())); - policySource.captureSynchronized(binding); coordinator.releaseApplicationSlot(binding); return binding; } private static DraftCommitBinding policyBinding( - TargetProof target, String expectedEpoch, String worldDisplayName) { + TargetProof target, String baseReference, String expectedEpoch, String worldDisplayName) { var policy = RealmEntryPolicy.parse( "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"" @@ -532,7 +536,7 @@ private static DraftCommitBinding policyBinding( target, UUID.randomUUID(), UUID.randomUUID(), - "ISOLATED-initial-source-base", + baseReference, List.of( new DraftCommitBinding.RevisionPayload( "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), @@ -546,6 +550,47 @@ private static DraftCommitBinding policyBinding( expectedEpoch))); } + private static SourceHead currentSourceHead( + TargetProof target, DSLContext dsl, GameDesignSourceRepository sources) { + var row = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT source_epoch, visible_commit_id, genesis_receipt_id " + + "FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()), + "fresh Draft fixture must retain its actual policy source head"); + UUID visibleCommit = row.get("visible_commit_id", UUID.class); + UUID genesisReceipt = row.get("genesis_receipt_id", UUID.class); + UUID sharedGenesisReceipt = + sources + .readGenesis(target) + .orElseThrow( + () -> new IllegalStateException("fresh Draft fixture lacks shared genesis")) + .policy() + .receiptId(); + if (!sharedGenesisReceipt.equals(genesisReceipt)) { + throw new IllegalStateException("policy source head differs from shared genesis receipt"); + } + String baseReference = + visibleCommit == null ? "genesis:" + sharedGenesisReceipt : visibleCommit.toString(); + return new SourceHead(row.get("source_epoch", String.class), baseReference); + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private record SourceHead(String sourceEpoch, String baseReference) {} + private static void assertRejectedHeaderClonesPreserveOriginal( Fixture fixture, RealmPolicyPublishedEvidence.PublishedSet original) { String targetProofError = "published realm policy set requires a closed complete TargetProof"; @@ -760,11 +805,17 @@ GameDesignPublicationOperation prepare(boolean capturePolicySource) throws Excep return tx( () -> { try { - var operation = IsolatedPublicationOwnerSetup.retain(dsl, target, 1); + var sources = new GameDesignSourceRepository(dsl); + String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked( + dsl, + target, + 1, + "ISOLATED remote owner transaction proof", + sourceBaseReference); if (capturePolicySource) { - policySource.captureSynchronized( - operation.account().input().selection().selectedCommit()); - policySource.freeze(operation); + sources.freeze(operation); } return operation; } catch (Exception failure) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java index c645b1dd4f..bb301ab9dd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -7,6 +7,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -46,17 +47,26 @@ void parsesOnlyClosedDigestBoundOperationsAndRetainsExactPayloadAndProvenance() var malformed = List.of( - CommandSource.upsertPayload(definition) - .replace("\"operation\":\"UPSERT\"", "\"operation\":\"UPSERT\",\"extra\":true"), - "{\"schemaVersion\":1,\"revisionKind\":\"UNSUPPORTED\",\"operation\":\"DELETE\",\"commandId\":\"look\"}", - CommandSource.upsertPayload(definition) - .replace("\"schemaVersion\":1", "\"schemaVersion\":2")); - for (String payload : malformed) { + Map.entry( + CommandSource.upsertPayload(definition) + .replace("\"operation\":\"UPSERT\"", "\"operation\":\"UPSERT\",\"extra\":true"), + "Closed command source operation fields are required"), + Map.entry( + "{\"schemaVersion\":1,\"revisionKind\":\"UNSUPPORTED\",\"operation\":\"DELETE\",\"commandId\":\"look\"}", + "Unsupported Game Design command source revision kind"), + Map.entry( + CommandSource.upsertPayload(definition) + .replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + "Unsupported command source operation schema")); + for (var malformedCase : malformed) { var bad = binding( - commitId, List.of(revision("0", revisionId, payload)), List.of(commandScope("0"))); + commitId, + List.of(revision("0", revisionId, malformedCase.getKey())), + List.of(commandScope("0"))); assertThatThrownBy(() -> CommandSource.mutations(bad)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(malformedCase.getValue()); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 69d6e6855b..3658997741 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -380,6 +381,113 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { .recordFullVersionParticipantDigests(any(String.class), any(List.class)); } + @ParameterizedTest + @EnumSource( + value = VersionLifecycleState.class, + names = {"PUBLISHED", "ACTIVE", "RETIRED"}) + void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting( + VersionLifecycleState lifecycleState) throws Exception { + SelectedSucceededReplayFixture fixture = selectedSucceededReplayFixture(lifecycleState); + + PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish(fixture.request()); + + assertEquals("SUCCEEDED", snapshot.status()); + verify(publishAttemptRepository).requirePublishedOperation(fixture.attempt()); + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + assertNoPublicationWrites(); + } + + @Test + void selectedSucceededReplayRejectsMismatchedCommittedBundle() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.ACTIVE); + String changedWorkflowId = fixture.request().publishWorkflowId() + ":changed"; + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(withWorkflowId(fixture.bundle(), changedWorkflowId))); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); + + assertNoPublicationWrites(); + } + + @Test + void selectedSucceededReplayRejectsMismatchedCommittedArtifact() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.RETIRED); + VersionAssetArtifactStateDto artifact = fixture.artifact(); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.of( + new VersionAssetArtifactStateDto( + artifact.tenantId(), + artifact.versionId(), + artifact.exportedVersionNumber(), + "PURGED", + artifact.stateEpoch(), + artifact.manifestHash(), + artifact.lastWorkflowId(), + artifact.lastErrorCode(), + artifact.lastErrorMessage(), + artifact.updatedAt(), + artifact.exportedManifestAssetKeys()))); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); + + assertNoPublicationWrites(); + } + + @Test + void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.ACTIVE); + org.mockito.Mockito.doThrow( + new IllegalStateException("ISOLATED retained publication gate mismatch")) + .when(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); + + verify(publishGateService) + .assertGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); + assertNoPublicationWrites(); + } + + @Test + void selectedSucceededReplayRejectsRecordedDigestMismatch() throws Exception { + SelectedSucceededReplayFixture fixture = + selectedSucceededReplayFixture(VersionLifecycleState.RETIRED); + org.mockito.Mockito.doThrow( + new IllegalStateException("ISOLATED retained participant digest mismatch")) + .when(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.request())); + + verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests( + "tenant-1", PublishType.FULL_VERSION, fixture.participantDigests()); + assertNoPublicationWrites(); + } + @Test void succeededReplayRejectsMismatchedCommittedBundleIdentity() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -2417,6 +2525,178 @@ private SelectedPublishFixture selectedPublishFixture(int versionNumber) { return new SelectedPublishFixture(reservation, request, attempt, version); } + private SelectedSucceededReplayFixture selectedSucceededReplayFixture( + VersionLifecycleState lifecycleState) throws Exception { + TargetProof target = + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + // Stipulated original upstream bytes, not live Account or World producer proof. This closed + // operation carries one typed World graph, reviewed base, selection, and publication request. + var operation = + IsolatedPublicationOperationFixtures.fresh( + target, "genesis:66666666-6666-4666-8666-666666666666"); + var selected = operation.account().input().selection(); + SelectionSnapshot reservation = + new SelectionSnapshot( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + OffsetDateTime.parse("2026-10-08T00:00:00Z")); + PublishWorkflowRequest request = selectedRequest(reservation); + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, request.publishWorkflowId()); + attempt.setRequestDigest(reservation.selection().digest()); + Version version = fullVersion(10L, 1, lifecycleState); + version.setVersionStateEpoch( + switch (lifecycleState) { + case PUBLISHED -> 6L; + case ACTIVE -> 7L; + case RETIRED -> 8L; + default -> + throw new IllegalArgumentException("terminal replay fixture requires a release"); + }); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + + // The retained v2 selector payload must bind to the exact selected World commit and original + // publication request, regardless of the Version's later legal lifecycle state. + WorldPublishedStartLocationEvidence selectedEvidence = operation.world(); + List participantDigests = + PublishedWorldSelectorFixtures.participants( + 10L, selectedEvidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + PublishedReleaseBundleDto bundle = + new PublishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v2", + request.publishWorkflowId(), + MANIFEST_HASH, + List.of("manifest.json"), + participantDigests, + List.of(), + "generation-revision", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(List.of("manifest.json")), + selectedEvidence); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PUBLISHED", + 2L, + MANIFEST_HASH, + request.publishWorkflowId(), + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + + when(authoredSelections.readByPublishRequest( + request.intent().canonicalTenantId(), request.publishRequestId())) + .thenReturn(Optional.of(reservation)); + when(publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId())) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); + return new SelectedSucceededReplayFixture( + request, attempt, bundle, participantDigests, artifact); + } + + private void assertNoPublicationWrites() { + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(versionAssetArtifactService, never()) + .markPublished( + any(String.class), + any(Long.class), + any(Long.class), + any(String.class), + any(String.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .recordFullVersionParticipantDigests(any(String.class), any(List.class)); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(recordedParticipantDigestService, never()) + .recordVerifiedDigests( + any(String.class), any(PublishType.class), any(String.class), any(List.class)); + verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + } + + private static PublishedReleaseBundleDto withWorkflowId( + PublishedReleaseBundleDto bundle, String workflowId) { + return new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + bundle.attestationSchemaVersion(), + workflowId, + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + bundle.worldPublishedStartLocationEvidence()); + } + private VersionAssetArtifactStateDto stagedArtifact( PublishWorkflowRequest request, Version version) { return new VersionAssetArtifactStateDto( @@ -2480,6 +2760,13 @@ private record SelectedPublishFixture( PublishAttempt attempt, Version version) {} + private record SelectedSucceededReplayFixture( + PublishWorkflowRequest request, + PublishAttempt attempt, + PublishedReleaseBundleDto bundle, + List participantDigests, + VersionAssetArtifactStateDto artifact) {} + private static ExportedAssetManifest exportedManifest(List usageKeys) { return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); } From a8cd0996baf7639c68255378a7cdf523539781b4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:10:08 +1300 Subject: [PATCH 29/29] Reject absent command deletions and prove valid source fixture mutations --- .../game-design-service/api-contracts.md | 2 ++ .../gamedesign/publication/CommandSource.java | 4 ++- ...lmPolicySourcePostgresIntegrationTest.java | 17 ++++++++-- .../publication/CommandSourceTest.java | 31 +++++++++++++------ 4 files changed, 40 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index c62a8841d5..b2969c2bb1 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -158,6 +158,8 @@ The [durable Draft coordinator](./version-control.md#design-time-synchronization The existing closed UPSERT owner envelope is `{"revisionKind":"REALM_ENTRY_POLICY","logicalRevisionId":...,"policy":...}`. Explicit deletion uses exactly `{"revisionKind":"REALM_ENTRY_POLICY","logicalRevisionId":...,"operation":"DELETE","worldSlug":...,"realmSlug":...}` with canonical selectors. Mutations apply in canonical revision order; deletion rejects an absent `(worldSlug, realmSlug)` selector or a `logicalRevisionId` that does not match that effective policy, and removes only that exact selector. Omission is not deletion. Tenant/version-wide `realmSlug` uniqueness is checked on the final effective set, so a commit may delete a realm from one world and explicitly upsert it in another. +Command-source mutations also apply in canonical revision order, and explicit deletion rejects a stable command key absent from the effective command set. + Publication freezes that exact selected synchronized source and the complete original publication operation once. Source mutation and freeze share the owning Version serialization boundary. The effective published set has at most 128 policies, unique `(worldSlug, realmSlug)` selectors, tenant/version-wide `realmSlug` uniqueness, and exactly one `visible=true && publicProduction=true` policy. Game Design persists separate immutable policy rows and allocates each policy UUID once. Exact retry returns the original identities and bytes; conflicting evidence cannot silently select another source or bundle. Policy evidence binds canonical tenant/version and owner provenance, original source commit/revision/logical identity, the selected source capture, and the genuine sealed publication's workflow, manifest and release-content identity/digest. A source capture alone is not `PUBLISHED`. These separate rows and digests do not rewrite the closed release, terminal, launch-descriptor or release-attestation bytes. `ResolvePublishedRealmEntryPolicy` proves one exact selector; `ListPublishedRealmEntryPolicies` proves the complete ordered set, exact count and set digest. Both authenticate the same-namespace Game Session workload before decoding or owner access, independently read the exact canonical owner target and its full Version in `PUBLISHED` or `ACTIVE`, and verify the frozen source against the actual sealed publication and immutable release. Missing, contradictory, wrong-operation or mismatched digest evidence denies the complete response. No policy is inferred from a bundle, current mutable revisions or a caller's publication claim. The set read is complete-or-error: a bounded read detects an oversized set instead of returning a truncated prefix, and individual-selector proof cannot substitute for complete-set cardinality. Private owner row keys remain provenance, not public tenant/version identity. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index 40a0d14213..e833008d33 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -260,7 +260,9 @@ public static List replay(List inherited, List previousOrder = mutation.revisionOrder(); commitId = mutation.commitId(); if (mutation.operation() == OperationKind.DELETE) { - effective.remove(mutation.stableKey()); + if (effective.remove(mutation.stableKey()) == null) { + throw new IllegalArgumentException("Cannot delete an absent command definition key"); + } } else { effective.put( mutation.stableKey(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index 1f02c6a541..5280ade5c9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -254,7 +254,13 @@ void sourceComposesOneOwnerResultAndCommandOnlyFenceInheritsPolicy() { "1", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, - CommandSource.deletePayload("ISOLATED-command")); + CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"ISOLATED-command\"," + + "\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," + + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}")); var commandScope = new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -985,8 +991,13 @@ private static DraftCommitBinding commandOnlyBinding( "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, - "{\"revisionKind\":\"COMMAND_DEFINITION\",\"schemaVersion\":1," - + "\"operation\":\"DELETE\",\"commandId\":\"ISOLATED-command\"}")), + CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"ISOLATED-command\"," + + "\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," + + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java index bb301ab9dd..9a160c7cbf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -86,14 +86,7 @@ void replaysStableKeyUpsertAndExplicitDeleteInRevisionOrderWithoutLosingAuthorsh commit, CommandSource.OperationKind.UPSERT, "LOOK", - exactDefinition), - new CommandSource.Mutation( - "2", - UUID.randomUUID(), - commit, - CommandSource.OperationKind.DELETE, - "absent", - null)); + exactDefinition)); var result = CommandSource.replay(inherited, operations); assertThat(result).hasSize(1); @@ -102,8 +95,26 @@ void replaysStableKeyUpsertAndExplicitDeleteInRevisionOrderWithoutLosingAuthorsh assertThat(result.getFirst().sourceCommitId()).isEqualTo(commit); assertThat(result.getFirst().sourceRevisionId()).isEqualTo(upsertRevision); assertThat(CommandSource.replay(inherited, List.of())).containsExactlyElementsOf(inherited); - assertThat(CommandSource.replay(result, List.of(operations.get(2)))) - .containsExactlyElementsOf(result); + var delete = + new CommandSource.Mutation( + "2", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "LOOK", null); + assertThat(CommandSource.replay(result, List.of(delete))).isEmpty(); + var absentDelete = + new CommandSource.Mutation( + "3", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "absent", null); + assertThatThrownBy(() -> CommandSource.replay(inherited, List.of(absentDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + assertThatThrownBy(() -> CommandSource.replay(List.of(), List.of(absentDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + var secondDelete = + new CommandSource.Mutation( + "1", UUID.randomUUID(), commit, CommandSource.OperationKind.DELETE, "look", null); + assertThatThrownBy( + () -> CommandSource.replay(inherited, List.of(operations.getFirst(), secondDelete))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); assertThatThrownBy( () -> CommandSource.replay(inherited, List.of(operations.get(1), operations.get(0)))) .isInstanceOf(IllegalArgumentException.class);