From c9b79f36a44281b538c5eee7440f0cf0a6952cb0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:14:35 +1300 Subject: [PATCH 01/36] Prepare standalone selected-owner source disclosure --- .../account-service/runtime-and-data.md | 2 + .../game-design-service/version-control.md | 2 + design/project-management/ai-observations.md | 2 + .../player-access-and-session.md | 4 + ...ted_owner_intake_source_read_service.proto | 27 + ...selected_owner_intake_source_service.proto | 27 + .../DraftAuthorizationFenceRepository.java | 31 + ...ectedOwnerIntakeSourceReadGrpcService.java | 93 +++ ...tSelectedOwnerIntakeSourceReadService.java | 104 +++ ...wnerIntakeSourceReservationRepository.java | 453 ++++++++++++ ...edOwnerIntakeSourceReservationService.java | 199 ++++++ ...ected_owner_intake_source_reservations.sql | 428 +++++++++++ ...rceReservationPostgresIntegrationTest.java | 254 +++++++ ...orizationFenceSelectedOwnerIntakeTest.java | 262 +++++++ ...dOwnerIntakeSourceReadGrpcServiceTest.java | 296 ++++++++ ...ectedOwnerIntakeSourceReadServiceTest.java | 199 ++++++ ...IntakeSourceReservationRepositoryTest.java | 38 + ...nerIntakeSourceReservationServiceTest.java | 403 +++++++++++ .../AccountControlUiOriginalOrderFixture.java | 10 + .../AccountControlUiOwnerSourcesFixture.java | 10 +- ...pcSelectedOwnerIntakeSourceReadClient.java | 149 ++++ .../SelectedOwnerIntakeSourceReadClient.java | 6 + ...SelectedOwnerIntakeSourceReadEvidence.java | 73 ++ ...lectedOwnerIntakeSourceReadProtoCodec.java | 91 +++ .../SelectedOwnerIntakeSourceReadScope.java | 125 ++++ .../gamedesign/BrandingSourceSnapshot.java | 179 +++++ .../common/gamedesign/CommandSnapshot.java | 107 +++ .../common/gamedesign/CommandSource.java | 4 +- .../GrpcSelectedOwnerIntakeSourceClient.java | 151 ++++ .../SelectedOwnerIntakeSourceClient.java | 8 + .../SelectedOwnerIntakeSourceContent.java | 248 +++++++ .../SelectedOwnerIntakeSourceProtoCodec.java | 120 ++++ ...electedOwnerIntakeClientLifecycleTest.java | 276 +++++++ ...edOwnerIntakeSourceReadClientMtlsTest.java | 529 ++++++++++++++ ...edOwnerIntakeSourceReadProtoCodecTest.java | 224 ++++++ ...electedOwnerIntakeSourceReadScopeTest.java | 405 +++++++++++ .../common/gamedesign/CommandSourceTest.java | 43 ++ ...lectedOwnerIntakeSourceClientMtlsTest.java | 673 ++++++++++++++++++ .../SelectedOwnerIntakeSourceContentTest.java | 437 ++++++++++++ ...lectedOwnerIntakeSourceProtoCodecTest.java | 301 ++++++++ ...SelectedOwnerIntakeSourceTestFixtures.java | 84 +++ services/game-design-service/build.gradle.kts | 2 + .../BrandingSourceApplication.java | 44 ++ .../publication/BrandingSourceRepository.java | 543 ++++++++++++++ .../publication/BrandingSourceSnapshot.java | 106 +++ .../publication/CommandApplication.java | 1 + .../publication/CommandSnapshot.java | 97 +-- .../gamedesign/publication/CommandSource.java | 653 ----------------- .../publication/CommandSourceRepository.java | 17 +- ...nSelectedOwnerIntakeSourceGrpcService.java | 89 +++ ...nSelectedOwnerIntakeSourceReadService.java | 92 +++ .../GameDesignSourceRepository.java | 255 ++++++- .../SelectedOwnerIntakeSourceExport.java | 119 ++++ .../PublishedReleaseBundleRepository.java | 2 +- ...urceDisclosurePostgresIntegrationTest.java | 238 +++++++ ...BrandingSourcePostgresIntegrationTest.java | 468 ++++++++++++ ...meDesignSourcePostgresIntegrationTest.java | 16 +- ...lmPolicySourcePostgresIntegrationTest.java | 6 +- ...StorageUpgradePostgresIntegrationTest.java | 2 +- ...teConfigSourcePostgresIntegrationTest.java | 16 +- .../publication/BrandingSourceTest.java | 148 ++++ .../GameDesignReviewedBaseEvidenceTest.java | 2 +- .../publication/CommandSourceTest.java | 5 +- ...ectedOwnerIntakeSourceGrpcServiceTest.java | 238 +++++++ ...ectedOwnerIntakeSourceReadServiceTest.java | 288 ++++++++ .../SelectedOwnerIntakeSourceExportTest.java | 228 ++++++ 66 files changed, 9981 insertions(+), 771 deletions(-) create mode 100644 protos/account/v1/selected_owner_intake_source_read_service.proto create mode 100644 protos/game-design/v1/selected_owner_intake_source_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java delete 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/GameDesignSelectedOwnerIntakeSourceGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java create mode 100644 services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 73f4056110..d5b9068bdb 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1006. It preserves the actual V1005 combined parent and prior protection/disposal guards. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. + The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index d05574f866..de2be5395b 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,6 +6,8 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status +The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing V1007 storage, and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). + Standalone Template source/reference owners, selected-publication reservation and the exact original StartSession template read are prepared over existing guarded storage. They remain unregistered; qualified owner-local storage does not supply genuine Account, World or immutable-release authority. Current source, proof and retention limitations belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). The prepared selected gameplay-rule source export and intake/receipt composition remain standalone and unregistered; they add no full-version publication authority or runtime rule activation. The [gameplay-rule retention tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification, exact owner composition and controlled-input limits. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 60f0dc94ab..034fd1f4d2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -338,3 +338,5 @@ Entry format: - Qualification: the 3 GiB setting is not a restoration of an earlier default; the shared 1500m setting predates the recent guard since August 28. Worker, test, and code-generation JVM memory remains additional, and the hosted module runner's explicit 2500m setting is unchanged. - `2026-10-15`: Classes-only foreign-owner proof artifacts intentionally omit application and Flyway resources. A composed test that reads another owner’s migrations from disk must declare those directories as task inputs; otherwise a SQL-only change can leave the composition up-to-date. The selected Game Logic proof exposed this after its forward migration was reconciled, and Game Design now tracks the foreign Game Logic and World migration directories. + +- `2026-10-15`: Allocate forward migrations against the actual resolved Flyway history, including shared Saga resources and later service-owned migrations. The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history. The receiving Account parent already reaches V1005, while Saga reaches V1002. Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ca1860b05b..a309fa61f7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Selected recipient source intake preparation + +The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1006 follows the actual V1005 plus Saga parent; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof retains parent rows, source bytes, history and xmin, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. + ### Original StartSession protected activation source The standalone source prepares Account activation-protection acquisition, retained readback and authenticated World-terminal settlement over the existing V1003/V1004 guards. Acquisition requires the exact original COMMITTED World participation, reads its immutable historical Game Session witness without rewriting or rearming it, and independently obtains a fresh current attempt and a complete operation-bound canonical STARTING association. The Account callback and SQL database-clock/source-currentness guards remain required. Historical witness storage never substitutes for fresh authority. The canonical owner read binds the original tuple and mutation/attempt/fence to the actual pending Game Session owner and immutable pins; World retains its existing caller-specific selector path. diff --git a/protos/account/v1/selected_owner_intake_source_read_service.proto b/protos/account/v1/selected_owner_intake_source_read_service.proto new file mode 100644 index 0000000000..92661916d5 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_source_read_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered preliminary Entity/Automation source-scope confirmation. +// This proof is not finalized retention authority or evidence of a complete source census. +service AccountSelectedOwnerIntakeSourceReadService { + rpc ReadSourceScope(SelectedOwnerIntakeSourcePermissionRequest) + returns (SelectedOwnerIntakeSourcePermissionResponse); +} + +message SelectedOwnerIntakeSourcePermissionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + bytes preliminary_source_scope = 6; + string preliminary_scope_digest = 7; +} + +message SelectedOwnerIntakeSourcePermissionResponse { + SelectedOwnerIntakeSourcePermissionRequest request = 1; + bool permitted = 2; +} diff --git a/protos/game-design/v1/selected_owner_intake_source_service.proto b/protos/game-design/v1/selected_owner_intake_source_service.proto new file mode 100644 index 0000000000..c3947bcae8 --- /dev/null +++ b/protos/game-design/v1/selected_owner_intake_source_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package game_design.v1; +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone, unregistered transport for complete selected-owner source content. +service GameDesignSelectedOwnerIntakeSourceService { + rpc ReadSelectedSource(SelectedOwnerIntakeSourceRequest) + returns (SelectedOwnerIntakeSourceResponse); +} + +message SelectedOwnerIntakeSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + bytes preliminary_source_scope = 6; + string preliminary_scope_digest = 7; +} + +message SelectedOwnerIntakeSourceResponse { + SelectedOwnerIntakeSourceRequest request = 1; + bytes selected_source_content = 2; + string selected_source_digest = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index c7c95d475c..ca79fda409 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -267,6 +267,7 @@ public void requireDisclosurePreparation(List exactSources) { } requireNoPendingPublication(sources); requireNoPendingGameLogicIntake(sources); + requireNoPendingSelectedOwnerIntakeSourceRead(sources); requireNoPendingWorldParticipation(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); @@ -360,6 +361,36 @@ public void requireGameLogicIntakeAdmission( } } + /** Distinct recipient-bound intake requires the exact settled original author selection. */ + public void requireSelectedOwnerIntakeAdmission( + List sources, DraftCommitBinding selected) { + requirePublicationAdmission(sources); + Objects.requireNonNull(selected, "selected Draft binding is required"); + Record originalRow = dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE", + selected.requestId(), selected.commitId()); + if (originalRow == null) throw new IllegalStateException("Selected author operation is unavailable"); + DraftAuthorizationFenceBinding original = originalBinding(originalRow); + if (!Arrays.equals(original.gameDesignBinding(), selected.canonicalBytes()) + || !Ordering.COMMIT_ORDER.name().equals(originalRow.get("ordering", String.class)) + || settlement(original, Ordering.COMMIT_ORDER) != Settlement.COMMITTED) { + throw new IllegalStateException( + "Exact selected original author operation must be committed and settled"); + } + } + + private void requireNoPendingSelectedOwnerIntakeSourceRead(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT source.operation_id FROM account_selected_owner_intake_source_read_sources source " + + "WHERE source.source_key = ? " + + "AND account_selected_owner_intake_source_read_is_pending(source.operation_id)", + source.key()).isEmpty()) { + throw new IllegalStateException("Selected owner intake source read remains pending"); + } + } + } + private boolean hasPendingGameLogicIntake(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java new file mode 100644 index 0000000000..29c3b6a369 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone preliminary Entity/Automation source permission receiver; never registered. */ +public final class AccountSelectedOwnerIntakeSourceReadGrpcService + extends AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceImplBase { + private final AccountSelectedOwnerIntakeSourceReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeSourceReadGrpcService( + AccountSelectedOwnerIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-owner source reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readSourceScope( + SelectedOwnerIntakeSourcePermissionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() > SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request + decoded; + try { + decoded = SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + var confirmed = + owner.readSourceScope(decoded.scope(), decoded.intendedReader(), decoded.purpose()); + if (confirmed == null + || !java.util.Arrays.equals(decoded.scope().canonicalBytes(), confirmed.canonicalBytes()) + || !decoded.scope().digest().equals(confirmed.digest())) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + observer.onNext(SelectedOwnerIntakeSourceReadProtoCodec.toResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + if (code == Status.Code.PERMISSION_DENIED || code == Status.Code.FAILED_PRECONDITION) { + observer.onError(Status.fromCode(code).asRuntimeException()); + } else { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } catch (IllegalArgumentException | IllegalStateException staleOrChanged) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java new file mode 100644 index 0000000000..87f49ba243 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact pending Entity/Automation source readback; never finalizes owner retention. + */ +public final class AccountSelectedOwnerIntakeSourceReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final AccountControlUiCoordination registry; + private final TransactionTemplate transaction; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner repository is intentionally shared and never exposed to callers") + public AccountSelectedOwnerIntakeSourceReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AccountControlUiCoordination registry, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.registry = Objects.requireNonNull(registry); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** + * Confirms one exact, still-live preliminary source reservation. The registry read is outside + * both independent READ_COMMITTED SQL transactions; this result grants no retention authority. + */ + public SelectedOwnerIntakeSourceReadScope readSourceScope( + SelectedOwnerIntakeSourceReadScope scope, String intendedReader, String purpose) { + requireGameDesignPeer(); + Objects.requireNonNull(scope, "source-read scope is required"); + if (!namespace.equals(scope.targetNamespace()) + || !intendedReader(scope.owner()).equals(intendedReader) + || !scope.intendedReader().equals(intendedReader) + || !scope.purpose().equals(purpose)) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + requireOutsideSql(); + var current = + Objects.requireNonNull( + transaction.execute(ignored -> repository.sourceReadCurrentness(scope))); + var active = registry.readActive(current.tokenHash()); + if (!current.registryDigest().equals(DraftAuthorizationFenceBinding.digest(active))) { + throw Status.FAILED_PRECONDITION + .withDescription("Original creator registry evidence is no longer exact") + .asRuntimeException(); + } + return Objects.requireNonNull( + transaction.execute( + ignored -> { + repository.readSourceScope(scope, current); + return scope; + })); + } + + private String intendedReader(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) + throw Status.PERMISSION_DENIED.asRuntimeException(); + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireOutsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner source read requires independent Account transactions") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java new file mode 100644 index 0000000000..85bbbc1e1e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -0,0 +1,453 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.ArrayList; +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.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable Entity/Automation preliminary source-read reservations and exact abort recovery. */ +public final class AccountSelectedOwnerIntakeSourceReservationRepository { + private static final String RESERVATIONS = + "account_selected_owner_intake_source_read_reservations"; + private static final String SOURCES = "account_selected_owner_intake_source_read_sources"; + private static final String ABORTS = "account_selected_owner_intake_source_read_aborts"; + + private final DSLContext dsl; + + public AccountSelectedOwnerIntakeSourceReservationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + public enum State { + RESERVED, + ABORTED + } + + /** Historical evidence only. RESERVED does not imply a live source-read permission. */ + public record Recovery(SelectedOwnerIntakeSourceReadScope scope, State state) { + public Recovery { + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(state, "state"); + } + } + + /** Exact database evidence sampled before the independent active-registry read. */ + record SourceReadCurrentness( + String tokenHash, + String registryDigest, + long expiresAtEpochSecond, + String issuerEvidenceDigest, + String sourceVectorDigest) { + SourceReadCurrentness { + Objects.requireNonNull(tokenHash); + Objects.requireNonNull(registryDigest); + Objects.requireNonNull(issuerEvidenceDigest); + Objects.requireNonNull(sourceVectorDigest); + } + } + + SelectedOwnerIntakeSourceReadScope reserveSourceRead( + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + AccountControlUiActorService.Current current, + String namespace, + Runnable admission) { + requireTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(selected, "selected"); + requireOwner(owner); + Objects.requireNonNull(current, "current"); + Objects.requireNonNull(admission, "admission"); + + UUID tenantId = selected.target().canonicalTenantId(); + Record existing = + dsl.fetchOne( + "SELECT * FROM " + + RESERVATIONS + + " WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", + tenantId, + intakeRequestId); + if (existing != null) { + SelectedOwnerIntakeSourceReadScope original = + SelectedOwnerIntakeSourceReadScope.fromStored(existing.get("scope_bytes", byte[].class)); + requireReservation(existing, original); + requireSameScope(original, namespace, owner, selected, current.stored().accountId); + requireCurrentReservation(existing, current); + if (aborted(original)) throw new IllegalStateException("Original source-read scope aborted"); + return original; + } + + admission.run(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + current.stored().accountId, + selected); + dsl.execute( + "INSERT INTO " + + RESERVATIONS + + " (operation_id, fence_id, intake_request_id, owner, actor_account_uuid, tenant_uuid, " + + "version_uuid, scope_bytes, scope_digest, issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.operationId(), + scope.fenceId(), + intakeRequestId, + owner.name(), + scope.actorAccountId(), + tenantId, + selected.target().canonicalVersionId(), + scope.canonicalBytes(), + scope.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + for (var source : current.source().sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + scope.operationId(), + source.key(), + source.canonicalBytes()); + } + requireReservation(reservation(scope), scope); + return scope; + } + + Optional findSourceReadScope( + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + String namespace, + String originalTokenHash) { + requireTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(selected, "selected"); + requireOwner(owner); + Objects.requireNonNull(namespace, "namespace"); + Objects.requireNonNull(originalTokenHash, "originalTokenHash"); + var row = + dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE tenant_uuid = ? AND intake_request_id = ?", + selected.target().canonicalTenantId(), + intakeRequestId); + if (row == null) return Optional.empty(); + var scope = SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + requireReservation(row, scope); + requireSameScope(scope, namespace, owner, selected, scope.actorAccountId()); + var issuer = issuer(row.get("issuance_operation_id", UUID.class)); + if (!originalTokenHash.equals(issuer.tokenHash)) { + throw new IllegalArgumentException("Original creator credential differs from reservation"); + } + return Optional.of(scope); + } + + Recovery recoverSourceRead(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope)) return new Recovery(scope, State.ABORTED); + return new Recovery(scope, State.RESERVED); + } + + Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (!aborted(scope)) { + dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId()); + } + return new Recovery(scope, State.ABORTED); + } + + SourceReadCurrentness sourceReadCurrentness(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status)) + throw new IllegalStateException("Original creator issuance is no longer committed"); + return currentness(row, original); + } + + void readSourceScope(SelectedOwnerIntakeSourceReadScope scope, SourceReadCurrentness expected) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status) || !currentness(row, original).equals(expected)) { + throw new IllegalStateException("Exact current pending source-read scope required"); + } + // Use the Account database clock only after the final sorted source and operation locks. + // A caller clock sampled before lock acquisition is not a live-read expiry proof. + if (dsl.fetchOne( + "SELECT operation_id FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? AND status = 'COMMITTED'" + + " AND extract(epoch FROM clock_timestamp()) < expires_at_epoch_second", + original.operationId) + == null) { + throw new IllegalStateException("Original creator issuance expired before final readback"); + } + } + + private SourceReadCurrentness currentness( + Record row, AccountControlUiIssuanceRepository.Stored original) { + return new SourceReadCurrentness( + original.tokenHash, + DraftAuthorizationFenceBinding.digest(original.activeRegistry), + original.expiresAt.getEpochSecond(), + issuerEvidenceDigest(row, original), + sourceVectorDigest(row.get("operation_id", UUID.class))); + } + + private String issuerEvidenceDigest( + Record reservation, AccountControlUiIssuanceRepository.Stored original) { + Map evidence = new LinkedHashMap<>(); + evidence.put("operationId", original.operationId.toString()); + evidence.put("requestId", original.requestId.toString()); + evidence.put("jti", original.jti.toString()); + evidence.put("accountId", original.accountId.toString()); + evidence.put("tenantId", original.tenantId.toString()); + evidence.put("caller", original.caller); + evidence.put("callerContextId", original.callerContextId.toString()); + evidence.put("requestMacKeyId", original.requestMacKeyId); + evidence.put("requestDigest", original.requestDigest); + evidence.put("status", original.status); + evidence.put("tokenHash", original.tokenHash); + evidence.put("claims", Base64.getEncoder().encodeToString(original.claims)); + evidence.put("sources", Base64.getEncoder().encodeToString(original.sources)); + evidence.put("bundle", Base64.getEncoder().encodeToString(original.bundle)); + evidence.put("signerReceipt", Base64.getEncoder().encodeToString(original.signerReceipt)); + evidence.put("pendingRegistry", Base64.getEncoder().encodeToString(original.pendingRegistry)); + evidence.put("activeRegistry", Base64.getEncoder().encodeToString(original.activeRegistry)); + evidence.put("issuedAt", original.issuedAt.toString()); + evidence.put("expiresAt", original.expiresAt.toString()); + evidence.put("recoveryExpiresAt", original.recoveryExpiry.toString()); + evidence.put( + "issuanceOperationId", reservation.get("issuance_operation_id", UUID.class).toString()); + evidence.put("issuanceFence", reservation.get("issuance_fence", Long.class).toString()); + evidence.put( + "outboxCheckpoints", + Base64.getEncoder().encodeToString(reservation.get("outbox_checkpoints", byte[].class))); + return DraftAuthorizationFenceBinding.digest(AccountControlUiAuthority.canonical(evidence)); + } + + private String sourceVectorDigest(UUID operationId) { + List> vector = new ArrayList<>(); + for (Record row : + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + operationId)) { + vector.add( + Map.of( + "sourceKey", row.get("source_key", String.class), + "sourceEvidence", + Base64.getEncoder().encodeToString(row.get("source_evidence", byte[].class)))); + } + return DraftAuthorizationFenceBinding.digest( + AccountControlUiAuthority.canonical(Map.of("sources", vector))); + } + + private Record reservation(SelectedOwnerIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + } + + private boolean aborted(SelectedOwnerIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT operation_id FROM " + ABORTS + " WHERE operation_id = ?", scope.operationId()) + != null; + } + + private void lockReservedSources(SelectedOwnerIntakeSourceReadScope scope) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE operation_id = ?", scope.operationId()); + requireReservation(row, scope); + for (Record source : + dsl.fetch( + "SELECT source_key FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId())) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.get("source_key", String.class)) + == null) { + throw new IllegalStateException("Original preliminary source lock is unavailable"); + } + } + } + + private void requireReservation(Record row, SelectedOwnerIntakeSourceReadScope scope) { + if (row == null + || !Arrays.equals(scope.canonicalBytes(), row.get("scope_bytes", byte[].class)) + || !scope.digest().equals(row.get("scope_digest", String.class)) + || !scope.operationId().equals(row.get("operation_id", UUID.class)) + || !scope.fenceId().equals(row.get("fence_id", UUID.class)) + || !scope.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !scope.owner().name().equals(row.get("owner", String.class)) + || !scope.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !scope.selected().target().canonicalTenantId().equals(row.get("tenant_uuid", UUID.class)) + || !scope + .selected() + .target() + .canonicalVersionId() + .equals(row.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException("Original preliminary source scope is absent or changed"); + } + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!scope.actorAccountId().equals(original.accountId) + || !scope.selected().target().canonicalTenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) { + throw new IllegalArgumentException("Original preliminary creator evidence changed"); + } + var bundle = AccountControlUiIssuanceRepository.object(original.bundle); + Object fence = bundle.get("issuanceFence"); + if (!Long.toString(row.get("issuance_fence", Long.class)).equals(String.valueOf(fence))) { + throw new IllegalArgumentException("Original creator issuance fence changed"); + } + var checkpoints = bundle.get("outboxCheckpoints"); + if (!Arrays.equals( + AccountControlUiAuthority.canonical(checkpoints), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Original creator checkpoints changed"); + } + + Object storedSources = + AccountControlUiIssuanceRepository.object(original.sources).get("sources"); + List held = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId()); + if (!(storedSources instanceof List values) + || values.isEmpty() + || held.size() != values.size()) { + throw new IllegalArgumentException("Incomplete original creator source participation"); + } + for (int index = 0; index < values.size(); index++) { + if (!(values.get(index) instanceof String encoded)) { + throw new IllegalArgumentException("Malformed original creator source vector"); + } + byte[] exact = Base64.getDecoder().decode(encoded); + var source = DraftAuthorizationFenceBinding.SourceEvidence.fromStored(exact); + if (!source.key().equals(held.get(index).get("source_key", String.class)) + || !Arrays.equals(exact, held.get(index).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original complete source participation"); + } + } + } + + private AccountControlUiIssuanceRepository.Stored issuer(UUID operationId) { + Record issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + operationId); + if (issuer == null) throw new IllegalStateException("Original creator issuance is unavailable"); + return new AccountControlUiIssuanceRepository.Stored(issuer); + } + + private static void requireSameScope( + SelectedOwnerIntakeSourceReadScope scope, + String namespace, + Owner owner, + DraftCommitBinding selected, + UUID actorAccountId) { + if (!namespace.equals(scope.targetNamespace()) + || owner != scope.owner() + || !selected.equals(scope.selected()) + || !actorAccountId.equals(scope.actorAccountId())) { + throw new IllegalArgumentException("Intake request conflicts with its original source scope"); + } + } + + private static void requireOwner(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalArgumentException("Entity or Automation selected-source owner required"); + } + } + + private void requireCurrentReservation(Record row, AccountControlUiActorService.Current current) { + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status) + || !original.operationId.equals(current.stored().operationId) + || !original.accountId.equals(current.stored().accountId) + || !original.tenantId.equals(current.stored().tenantId) + || !original.tokenHash.equals(current.stored().tokenHash) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed original intake creator authority"); + } + List currentSources = current.source().sources(); + List heldSources = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + row.get("operation_id", UUID.class)); + if (currentSources.size() != heldSources.size()) + throw new IllegalArgumentException("Changed original intake source vector"); + for (int index = 0; index < currentSources.size(); index++) { + SourceEvidence source = currentSources.get(index); + Record held = heldSources.get(index); + if (!source.key().equals(held.get("source_key", String.class)) + || !Arrays.equals(source.canonicalBytes(), held.get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed original intake source vector"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java new file mode 100644 index 0000000000..571ae7e553 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered preliminary source-read producer; it grants no owner retention authority. */ +public final class AccountSelectedOwnerIntakeSourceReservationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + public AccountSelectedOwnerIntakeSourceReservationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.actors = Objects.requireNonNull(actors, "actors"); + this.fences = Objects.requireNonNull(fences, "fences"); + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Reserves one fresh source-read scope under the current creator, or recovers the exact existing + * request by its original credential hash. An expired credential cannot create a reservation. + */ + public SelectedOwnerIntakeSourceReadScope reserveSourceRead( + String compactJwt, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(selected, "selected"); + Objects.requireNonNull(environment, "current Account environment is required"); + + Optional retained = + findScope(compactJwt, intakeRequestId, owner, selected); + if (retained.isPresent()) { + var recovery = recover(retained.orElseThrow()); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation was aborted") + .asRuntimeException(); + return recovery.scope(); + } + + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + environment, + current -> { + fences.requireSelectedOwnerIntakeAdmission(current.source().sources(), selected); + return repository.reserveSourceRead( + intakeRequestId, owner, selected, current, namespace, () -> {}); + }); + } + + /** Historical exact recovery; it never renews authority or reopens an aborted reservation. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + SelectedOwnerIntakeSourceReadScope scope) { + requireGameDesignPeer(); + requireScope(scope); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.recoverSourceRead(scope))); + } + + /** Finds a lost first response from the original stable identity and exact credential hash. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + var scope = + findScope(originalCompactJwt, intakeRequestId, owner, selected) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); + return recover(scope); + } + + /** A definitive abort locks only this reservation's sorted source participation. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourceRead( + SelectedOwnerIntakeSourceReadScope scope) { + requireGameDesignPeer(); + requireScope(scope); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.abortSourceRead(scope))); + } + + /** Aborts the exact original operation even after credential expiry; it does not renew it. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourceRead( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + var scope = + findScope(originalCompactJwt, intakeRequestId, owner, selected) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); + return abortSourceRead(scope); + } + + private Optional findScope( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + if (originalCompactJwt == null + || originalCompactJwt.isEmpty() + || originalCompactJwt.length() > 16384 + || !StandardCharsets.US_ASCII.newEncoder().canEncode(originalCompactJwt)) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + String tokenHash = + AccountControlUiIssuanceRepository.hash( + originalCompactJwt.getBytes(StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); + } + + private void requireScope(SelectedOwnerIntakeSourceReadScope scope) { + if (scope == null + || !namespace.equals(scope.targetNamespace()) + || (scope.owner() != Owner.ENTITY_MANAGEMENT + && scope.owner() != Owner.AUTOMATION_SCRIPTING)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void requireOwner(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) + throw Status.INVALID_ARGUMENT + .withDescription("Entity or Automation selected-source owner required") + .asRuntimeException(); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner Account reservation requires an independent transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql b/services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql new file mode 100644 index 0000000000..c6764eb66c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql @@ -0,0 +1,428 @@ +-- Preliminary Entity/Automation source participation only; no finalized owner authorization. +CREATE TABLE account_selected_owner_intake_source_read_reservations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner IN ('ENTITY_MANAGEMENT', 'AUTOMATION_SCRIPTING')), + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 4194304), + scope_digest VARCHAR(71) NOT NULL CHECK (scope_digest ~ '^sha256:[0-9a-f]{64}$'), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (fence_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (intake_request_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (actor_account_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (version_uuid <> '00000000-0000-0000-0000-000000000000'), + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_selected_owner_intake_source_read_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_selected_owner_intake_source_read_lookup + ON account_selected_owner_intake_source_read_sources(source_key, operation_id); +CREATE TABLE account_selected_owner_intake_source_read_aborts ( + operation_id UUID PRIMARY KEY REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + aborted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_owner_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_reservations reservation + WHERE reservation.operation_id = operation_value + AND NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_aborts aborted + WHERE aborted.operation_id = reservation.operation_id)); +$$; + +CREATE FUNCTION account_selected_owner_intake_source_read_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + selected JSONB; + namespace_value TEXT; + owner_value TEXT; + purpose_value TEXT; + reader_value TEXT; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + marker TEXT; + ignored_frame BYTEA; + source_position INTEGER; + source_count INTEGER := 0; + seen TEXT[] := ARRAY[]::TEXT[]; + issuer account_control_ui_issuance_operations%ROWTYPE; + original account_draft_authorization_fences%ROWTYPE; + vector JSONB; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.issuance_operation_id; + IF NEW.producer_xid <> txid_current() + OR issuer.status IS DISTINCT FROM 'COMMITTED' + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second + OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Preliminary owner scope requires exact current committed creator evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') NOT IN ( + 'account-entity-intake-source-read/v1', 'account-automation-intake-source-read/v1') THEN + RAISE EXCEPTION 'Invalid preliminary owner scope schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO owner_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF owner_value IS DISTINCT FROM NEW.owner + OR (NEW.owner = 'ENTITY_MANAGEMENT' + AND convert_from(parsed, 'UTF8') <> 'account-entity-intake-source-read/v1') + OR (NEW.owner = 'AUTOMATION_SCRIPTING' + AND convert_from(parsed, 'UTF8') <> 'account-automation-intake-source-read/v1') THEN + RAISE EXCEPTION 'Preliminary owner schema and owner differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' THEN + RAISE EXCEPTION 'Invalid preliminary owner namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner operation' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner fence' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner request' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner actor' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_bytes, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + selected := convert_from(selected_bytes, 'UTF8')::JSONB; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR selected->>'requestId' IS NULL OR selected->>'commitId' IS NULL + OR jsonb_typeof(selected->'requiredOwners') IS DISTINCT FROM 'array' + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner complete selection' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO reader_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF reader_value IS DISTINCT FROM 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service' THEN + RAISE EXCEPTION 'Invalid preliminary owner intended reader' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO purpose_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF purpose_value IS DISTINCT FROM (CASE NEW.owner + WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_SOURCE' + WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_SOURCE' + ELSE NULL END) + OR p <> octet_length(NEW.scope_bytes) + 1 THEN + RAISE EXCEPTION 'Invalid preliminary owner purpose or trailing scope bytes' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT original FROM account_draft_authorization_fences + WHERE request_id = (selected->>'requestId')::UUID + AND commit_id = (selected->>'commitId')::UUID; + PERFORM account_draft_authorization_required_owners(original.binding); + FOR i IN 1..11 LOOP + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(original.binding, q); + IF parsed IS DISTINCT FROM selected_bytes + OR original.ordering IS DISTINCT FROM 'COMMIT_ORDER' + OR NOT account_draft_authorization_is_settled(original.operation_id) + OR EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks + WHERE operation_id = original.operation_id AND outcome IS DISTINCT FROM 'COMMITTED') + OR (SELECT count(*) FROM account_draft_authorization_owner_readbacks + WHERE operation_id = original.operation_id) + IS DISTINCT FROM cardinality(account_draft_authorization_required_owners(original.binding)) THEN + RAISE EXCEPTION 'Exact original creator Draft must be committed and settled before source read' + USING ERRCODE = '23514'; + END IF; + + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF jsonb_typeof(vector) IS DISTINCT FROM 'array' + OR jsonb_array_length(vector) < 1 + OR jsonb_array_length(vector) IS DISTINCT FROM + (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Incomplete preliminary complete Account source participation' + USING ERRCODE = '23514'; + END IF; + FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP + source_count := source_count + 1; + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid preliminary Account source schema' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF source_kind NOT IN ('ISSUER', 'ACCOUNT', 'TENANT', 'MEMBERSHIP', 'GLOBAL_ROLES', 'CREATOR_PARTY', 'HOSTED_TERMS') THEN + RAISE EXCEPTION 'Invalid preliminary Account source kind' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker = 'PRESENT' THEN + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source generation' USING ERRCODE = '23514'; END IF; + ELSIF marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid preliminary source generation marker' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source version' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker = 'PRESENT' THEN + SELECT frame_value, next_position INTO ignored_frame, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF octet_length(ignored_frame) = 0 THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint stream' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint sequence' USING ERRCODE = '23514'; END IF; + ELSIF marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint marker' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO ignored_frame, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + IF octet_length(source_bytes) > 131072 OR source_scope = '' + OR source_position <> octet_length(source_bytes) + 1 + OR octet_length(ignored_frame) = 0 + OR source_key_value = ANY(seen) + OR NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed or noncanonical preliminary complete Account source vector' + USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF source_count <> jsonb_array_length(vector) THEN + RAISE EXCEPTION 'Incomplete preliminary Account source vector' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_selected_owner_intake_source_read_complete + AFTER INSERT ON account_selected_owner_intake_source_read_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_complete_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_read_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Preliminary owner sources must accompany original reservation transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_read_source_validate + BEFORE INSERT ON account_selected_owner_intake_source_read_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_source_insert_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_read_abort_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM lock_row.source_key FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + PERFORM operation_id FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Only the exact active preliminary owner reservation can be aborted' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_read_abort_validate + BEFORE INSERT ON account_selected_owner_intake_source_read_aborts FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_abort_guard(); + +CREATE TRIGGER account_selected_owner_intake_source_read_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_reservations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_sources_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_aborts_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_aborts_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_aborts + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Keep the receiving V1005 assembled source-writer hook and add this independent owner participation. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; + owner_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT source.operation_id + FROM account_selected_owner_intake_source_read_sources source + WHERE source.source_key = ANY(source_keys) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY source.operation_id LOOP + PERFORM operation_id FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Selected owner intake source read remains pending for a required source' + USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled receiving Account source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; + +-- Pending reservations exclude terminal source changes after the receiving V1005 sorted source locks. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; + owner_guard TEXT := $guard$ IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = changed.source_key + WHERE changed.change_id = OLD.change_id + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ) THEN + PERFORM reservation.operation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = changed.source_key + JOIN account_selected_owner_intake_source_read_reservations reservation + ON reservation.operation_id = source.operation_id + WHERE changed.change_id = OLD.change_id + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY reservation.operation_id FOR UPDATE OF reservation NOWAIT; + RAISE EXCEPTION 'Pending selected owner intake source read excludes source-change completion' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one receiving V1005 source-change anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; + +-- A hosted-terms dispatch/retry cannot disclose a source vector still reserved for an owner read. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; + owner_guard TEXT := $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') + AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key + FROM account_draft_authorization_source_locks source_lock + JOIN ( + SELECT OLD.source_key AS source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id + ) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + IF EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ) THEN + PERFORM reservation.operation_id + FROM account_selected_owner_intake_source_read_sources source + JOIN account_selected_owner_intake_source_read_reservations reservation + ON reservation.operation_id = source.operation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY reservation.operation_id FOR UPDATE OF reservation NOWAIT; + RAISE EXCEPTION 'Pending selected owner intake source read excludes hosted-terms dispatch' + USING ERRCODE = '55P03'; + END IF; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one receiving V1005 hosted-terms dispatch anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..7a21673b7b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -0,0 +1,254 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.util.Map; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** PostgreSQL installation proof for V1006's additive selected-owner source reservations. */ +class AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest { + @Test + void installsV1006OverCombinedV1005ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() { + var fixture = new AccountPostgresIntegrationFixture(); + try { + fixture.start(); + String schema = "selected_owner_source_" + UUID.randomUUID().toString().replace("-", ""); + JdbcTemplate admin = new JdbcTemplate(fixture.dataSource()); + try { + admin.execute("CREATE SCHEMA " + quotedSchema(schema)); + DriverManagerDataSource source = fixture.dataSource(schema); + JdbcTemplate jdbc = new JdbcTemplate(source); + + migration(source, schema, "1005").migrate(); + assertVersionApplied(jdbc, schema, "1005"); + for (String version : List.of("137", "159", "160.1", "1000", "1001", "1002", "1003")) { + assertVersionApplied(jdbc, schema, version); + } + assertVersionNotApplied(jdbc, schema, "1006"); + var ownerDsl = org.jooq.impl.DSL.using( + new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy(source), + org.jooq.SQLDialect.POSTGRES); + var ownerTransaction = new org.springframework.transaction.support.TransactionTemplate( + new org.springframework.jdbc.datasource.DataSourceTransactionManager(source)); + ownerTransaction.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + var account = new net.firedevops.firemud.accountservice.entity.Account(); + account.setUsername("retained-parent-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("TEST_ONLY unused password verifier"); + account.setRole("player"); + var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(ownerDsl); + assertThat(ownerTransaction.execute(status -> accounts.save(account))).isNotNull(); + var retainedParent = retainedParentRows(jdbc); + String historyQuery = "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1006' ORDER BY installed_rank"; + var retainedHistory = jdbc.queryForList(historyQuery, String.class); + var protectionsGuard = functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])"); + var disposalGuard = functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()"); + assertThat(protectionsGuard).contains("account_start_session_admission_protections", "account_start_session_activation_protections"); + assertWorldSourceExclusionGuards( + functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"), + functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"), + functionDefinition(jdbc, "account_hosted_terms_disclosure_handoff_guard()")); + + migration(source, schema, "1006").migrate(); + assertVersionApplied(jdbc, schema, "1005"); + assertVersionApplied(jdbc, schema, "1006"); + assertThat(jdbc.queryForList(historyQuery, String.class)).isEqualTo(retainedHistory); + assertThat(retainedParentRows(jdbc)).isEqualTo(retainedParent); + assertThat(functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])")) + .isEqualTo(protectionsGuard); + assertThat(functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()")) + .isEqualTo(disposalGuard); + assertInstalledOwnerReservationSchema(jdbc, schema); + + String holdGuard = + functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"); + String sourceChangeGuard = + functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"); + String disclosureGuard = + functionDefinition(jdbc, "account_hosted_terms_disclosure_handoff_guard()"); + assertWorldSourceExclusionGuards(holdGuard, sourceChangeGuard, disclosureGuard); + assertThat(holdGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "account_selected_owner_intake_source_read_is_pending(source.operation_id)", + "Selected owner intake source read remains pending for a required source"); + assertThat(sourceChangeGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "Pending selected owner intake source read excludes source-change completion"); + assertThat(disclosureGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "Pending selected owner intake source read excludes hosted-terms dispatch"); + + assertMalformedReservationCreatesNoSourceRows(jdbc); + assertThat(retainedParentRows(jdbc)).isEqualTo(retainedParent); + } finally { + admin.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE"); + } + } finally { + fixture.stop(); + } + } + + private static Flyway migration( + DriverManagerDataSource source, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .target(MigrationVersion.fromVersion(targetVersion)) + .load(); + } + + /** Exact physical parent Account and its real source baselines; no credential authority implied. */ + private static Map> retainedParentRows(JdbcTemplate jdbc) { + Map> rows = new java.util.LinkedHashMap<>(); + for (String table : List.of("accounts", "account_authority_source_records")) { + rows.put(table, jdbc.queryForList("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + " t ORDER BY to_jsonb(t)::TEXT", String.class)); + } + return rows; + } + + private static void assertInstalledOwnerReservationSchema(JdbcTemplate jdbc, String schema) { + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM unnest(ARRAY[" + + "'account_selected_owner_intake_source_read_reservations', " + + "'account_selected_owner_intake_source_read_sources', " + + "'account_selected_owner_intake_source_read_aborts']::TEXT[]) " + + "AS names(name) WHERE to_regclass(name) IS NOT NULL", + Long.class))) + .isEqualTo(3L); + + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM pg_trigger trigger_row " + + "JOIN pg_class relation ON relation.oid = trigger_row.tgrelid " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE namespace.nspname = ? AND NOT trigger_row.tgisinternal " + + "AND trigger_row.tgname IN (" + + "'account_selected_owner_intake_source_read_complete', " + + "'account_selected_owner_intake_source_read_source_validate', " + + "'account_selected_owner_intake_source_read_abort_validate', " + + "'account_selected_owner_intake_source_read_immutable', " + + "'account_selected_owner_intake_source_read_no_truncate', " + + "'account_selected_owner_intake_source_read_sources_immutable', " + + "'account_selected_owner_intake_source_read_sources_no_truncate', " + + "'account_selected_owner_intake_source_read_aborts_immutable', " + + "'account_selected_owner_intake_source_read_aborts_no_truncate')", + Long.class, + schema))) + .isEqualTo(9L); + + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM pg_proc p " + + "JOIN pg_namespace n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? AND p.proname IN (" + + "'account_selected_owner_intake_source_read_is_pending', " + + "'account_selected_owner_intake_source_read_complete_guard', " + + "'account_selected_owner_intake_source_read_source_insert_guard', " + + "'account_selected_owner_intake_source_read_abort_guard')", + Long.class, + schema))) + .isEqualTo(4L); + } + + private static void assertMalformedReservationCreatesNoSourceRows(JdbcTemplate jdbc) { + UUID operationId = UUID.randomUUID(); + assertThatThrownBy( + () -> + jdbc.update( + "INSERT INTO account_selected_owner_intake_source_read_reservations (" + + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, 'UNDECLARED_OWNER', ?, ?, ?, " + + "decode('00', 'hex'), 'sha256:' || repeat('0', 64), ?, 1, " + + "decode('7b7d', 'hex'), decode('7b7d', 'hex'), decode('7b7d', 'hex'))", + operationId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(RuntimeException.class); + + assertThat(count(jdbc, "account_selected_owner_intake_source_read_reservations")).isZero(); + assertThat(count(jdbc, "account_selected_owner_intake_source_read_sources")).isZero(); + assertThat(count(jdbc, "account_selected_owner_intake_source_read_aborts")).isZero(); + } + + private static void assertWorldSourceExclusionGuards( + String holdGuard, String sourceChangeGuard, String disclosureGuard) { + assertThat(holdGuard) + .contains( + "account_ss_admission_assert_no_pending(source_keys)", + "account_start_session_world_participations participation", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "FOR UPDATE OF participation NOWAIT"); + assertThat(sourceChangeGuard) + .contains( + "account_ss_admission_assert_no_pending(", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes source-change completion"); + assertThat(disclosureGuard) + .contains( + "account_ss_admission_assert_no_pending(ARRAY(", + "OLD.status IN ('PREPARED', 'AMBIGUOUS')", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes hosted-terms dispatch"); + } + + private static String functionDefinition(JdbcTemplate jdbc, String signature) { + return Objects.requireNonNull( + jdbc.queryForObject("SELECT pg_get_functiondef(?::regprocedure)", String.class, signature)); + } + + private static int count(JdbcTemplate jdbc, String table) { + return Objects.requireNonNull( + jdbc.queryForObject("SELECT count(*) FROM " + table, Integer.class)); + } + + private static void assertVersionApplied(JdbcTemplate jdbc, String schema, String version) { + assertThat(historyCount(jdbc, schema, version)).isEqualTo(1); + } + + private static void assertVersionNotApplied(JdbcTemplate jdbc, String schema, String version) { + assertThat(historyCount(jdbc, schema, version)).isZero(); + } + + private static int historyCount(JdbcTemplate jdbc, String schema, String version) { + return Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM " + + quotedSchema(schema) + + ".flyway_schema_history " + + "WHERE version = ? AND success", + Integer.class, + version)); + } + + private static String quotedSchema(String schema) { + return "\"" + schema + "\""; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java new file mode 100644 index 0000000000..38d6aacf84 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java @@ -0,0 +1,262 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account owner tests; PostgreSQL trigger installation is not proven here. */ +class DraftAuthorizationFenceSelectedOwnerIntakeTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void pendingSelectedOwnerReservationBlocksDisclosurePreparation() throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + + assertThatThrownBy( + () -> fixture.repository.requireDisclosurePreparation(List.of(fixture.currentSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Selected owner intake source read remains pending"); + + assertThat(fixture.fetchedSql) + .anyMatch(sql -> sql.contains("account_selected_owner_intake_source_read_sources")) + .noneMatch(sql -> sql.contains("SELECT * FROM account_draft_authorization_fences")); + assertThat(fixture.executedSql) + .noneMatch(sql -> sql.contains("UPDATE account_draft_authorization_fences")); + } + + @Test + void currentCreatorMaySelectAnotherActorsExactSettledOriginalDraft() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + UUID originalAuthor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID currentCreator = UUID.fromString("22222222-2222-4222-8222-222222222222"); + assertThat(fixture.originalBinding.actorAccountId()).isEqualTo(originalAuthor); + assertThat(fixture.currentSource.scopeId()).isEqualTo(currentCreator.toString()); + + fixture.repository.requireSelectedOwnerIntakeAdmission( + List.of(fixture.currentSource), fixture.selected); + + assertThat(fixture.fetchedSql) + .anyMatch(sql -> sql.contains("WHERE request_id = ? AND commit_id = ? FOR UPDATE")) + .anyMatch(sql -> sql.contains("account_draft_authorization_owner_readbacks")); + } + + @Test + void substitutedSelectedBindingCannotUseAnOriginalSettlement() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + DraftCommitBinding changed = + selected(fixture.selected.requestId(), fixture.selected.commitId(), "changed"); + + assertThatThrownBy( + () -> + fixture.repository.requireSelectedOwnerIntakeAdmission( + List.of(fixture.currentSource), changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed and settled"); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final Record lockRow = mock(Record.class); + private final DraftCommitBinding selected = + selected( + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "selected"); + private final UUID originalAuthor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private final SourceEvidence originalSource = source(originalAuthor); + private final UUID currentCreator = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private final SourceEvidence currentSource = source(currentCreator); + private final DraftAuthorizationFenceBinding originalBinding = originalBinding(); + private final Record originalRow = recordForBinding(originalBinding); + private final Result originalSources = result(List.of(sourceRow(originalSource))); + private final Result committedReadbacks = result(List.of(readbackRow(originalBinding))); + private final Result emptyRows = result(List.of()); + private final Result pendingRows = result(List.of(mock(Record.class))); + private final boolean pending; + private final List fetchedSql = new java.util.ArrayList<>(); + private final List executedSql = new java.util.ArrayList<>(); + private final DraftAuthorizationFenceRepository repository = + new DraftAuthorizationFenceRepository(dsl); + + private Fixture(boolean pending) throws Exception { + this.pending = pending; + doAnswer(invocation -> false).when(connection).getAutoCommit(); + doAnswer(invocation -> false).when(connection).isReadOnly(); + doAnswer(invocation -> Connection.TRANSACTION_READ_COMMITTED) + .when(connection) + .getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + executedSql.add(sql); + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + fetchedSql.add(sql); + if (sql.contains("account_selected_owner_intake_source_read_sources")) { + return pending ? pendingRows : emptyRows; + } + if (sql.contains("account_draft_authorization_owner_readbacks")) { + return committedReadbacks; + } + if (sql.contains("account_draft_authorization_sources WHERE operation_id")) { + return originalSources; + } + return emptyRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + fetchedSql.add(sql); + if (sql.contains("WHERE request_id = ? AND commit_id = ?")) return originalRow; + if (sql.contains("account_draft_authorization_source_locks")) return lockRow; + return null; + }) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private DraftAuthorizationFenceBinding originalBinding() { + var original = + new DraftAuthorizationFenceBinding( + UUID.fromString("55555555-5555-4555-8555-555555555555"), + selected.requestId(), + selected.commitId(), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + originalAuthor, + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + List.of(originalSource)); + return original.withRequiredOwners(); + } + } + + private static DraftCommitBinding selected(UUID request, UUID commit, String payload) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 9L, "tenant-key", 10L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + "rules", + "TENANT", + tenant.toString(), + "0"))); + } + + private static SourceEvidence source(UUID actor) { + return new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1, 2, 3}); + } + + private static Record recordForBinding(DraftAuthorizationFenceBinding binding) { + Record record = mock(Record.class); + doReturn(binding.operationId()).when(record).get("operation_id", UUID.class); + doReturn(binding.requestId()).when(record).get("request_id", UUID.class); + doReturn(binding.commitId()).when(record).get("commit_id", UUID.class); + doReturn(binding.fenceId()).when(record).get("fence_id", UUID.class); + doReturn(binding.canonicalBytes()).when(record).get("binding", byte[].class); + doReturn("COMMIT_ORDER").when(record).get("ordering", String.class); + return record; + } + + private static Record sourceRow(SourceEvidence source) { + Record row = mock(Record.class); + doReturn(source.key()).when(row).get("source_key", String.class); + doReturn(source.canonicalBytes()).when(row).get("source_evidence", byte[].class); + return row; + } + + private static Record readbackRow(DraftAuthorizationFenceBinding binding) { + OwnerReadback readback = + new OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {9}); + Record row = mock(Record.class); + doReturn(Owner.GAME_DESIGN.name()).when(row).get("owner", String.class); + doReturn(Outcome.COMMITTED.name()).when(row).get("outcome", String.class); + doReturn(readback.canonicalBytes()).when(row).get("readback", byte[].class); + return row; + } + + @SuppressWarnings("unchecked") + private static Result result(List rows) { + Result result = mock(Result.class); + doReturn(rows.size()).when(result).size(); + doReturn(rows.isEmpty()).when(result).isEmpty(); + doAnswer(invocation -> rows.iterator()).when(result).iterator(); + doAnswer(invocation -> rows.stream()).when(result).stream(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..7b9350cff7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Synthetic transport tests; these do not establish mutual TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReadGrpcServiceTest { + private static final int MAX_WIRE_BYTES = 8 * 1024 * 1024; + private static final int MAX_SCOPE_BYTES = 4 * 1024 * 1024; + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesExactGameDesignPeerAndRejectsEndUserBeforeDecodingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var malformed = + SelectedOwnerIntakeSourcePermissionRequest.newBuilder().setTargetNamespace("test").build(); + + var missing = new Collector(); + service.readSourceScope(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String caller : + List.of("account-service", "game-logic-service", "world-management-service")) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSourceScope(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "game-design-service") + .run(() -> service.readSourceScope(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var validPeerMalformed = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(malformed, validPeerMalformed)); + assertThat(validPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void confirmsEntityAndAutomationScopesAndEchoesTheExactRequest() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + when(owner.readSourceScope(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + + for (var scope : + List.of( + scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING))) { + var request = request(scope); + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getPermitted()).isTrue(); + assertThat(result.response.getRequest()).isEqualTo(request); + verify(owner).readSourceScope(scope, scope.intendedReader(), scope.purpose()); + } + } + + @Test + void rejectsWrongNamespaceBeforeOwnerAndRejectsWrongReaderPurposeOrDomain() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var original = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + + var wrongNamespace = new Collector(); + peer("test", "game-design-service") + .run( + () -> + service.readSourceScope( + original.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var wrongReader = + request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)).toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build(); + var readerResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongReader, readerResult)); + assertDeniedOrMalformed(readerResult); + + var wrongPurpose = + request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)).toBuilder() + .setPurpose("AUTOMATION_INTAKE_SOURCE") + .build(); + var purposeResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongPurpose, purposeResult)); + assertDeniedOrMalformed(purposeResult); + + var wrongDomain = + request(scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING)).toBuilder() + .setPurpose("ENTITY_INTAKE_SOURCE") + .build(); + var domainResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongDomain, domainResult)); + assertDeniedOrMalformed(domainResult); + verifyNoInteractions(owner); + } + + @Test + void rejectsUnknownMalformedTamperedDigestAndOversizedWireRequests() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var valid = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + var unknown = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {0, 1, 2})) + .build(); + var badDigest = valid.toBuilder().setPreliminaryScopeDigest("0".repeat(64)).build(); + var oversizedScope = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[MAX_SCOPE_BYTES + 1])) + .build(); + var oversized = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[MAX_WIRE_BYTES + 1])) + .build(); + + for (var request : List.of(unknown, badDigest, oversizedScope, oversized)) { + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void changedOwnerResponseAndStaleOrMissingEvidenceFailClosedWithSanitizedErrors() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var original = scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + var request = request(original); + var changed = + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + original.targetNamespace(), + UUID.randomUUID(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.selected()); + when(owner.readSourceScope(any(), any(), any())).thenReturn(changed); + var changedResult = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, changedResult)); + assertThat(changedResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + doReturn(null).when(owner).readSourceScope(any(), any(), any()); + var missingResult = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, missingResult)); + assertThat(missingResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + for (var failure : + List.of( + Status.FAILED_PRECONDITION.withDescription("credential-secret").asRuntimeException(), + new IllegalStateException("credential-secret"))) { + doThrow(failure).when(owner).readSourceScope(any(), any(), any()); + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.errorDescription).isNull(); + } + } + + @Test + void returnsPermissionDenialWithoutLeakingOwnerExceptionDetails() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var request = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + when(owner.readSourceScope(any(), any(), any())) + .thenThrow( + Status.PERMISSION_DENIED.withDescription("credential-secret").asRuntimeException()); + + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.errorDescription).isNull(); + } + + private static void assertDeniedOrMalformed(Collector result) { + assertThat(result.error).isIn(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + + private static SelectedOwnerIntakeSourcePermissionRequest request( + SelectedOwnerIntakeSourceReadScope scope) { + return SelectedOwnerIntakeSourceReadProtoCodec.toRequest( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request.create(scope.targetNamespace(), scope)); + } + + private static SelectedOwnerIntakeSourceReadScope scope(DraftCommitBinding.Owner owner) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + "test", + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static Context peer(String namespace, String workload) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + String errorDescription; + SelectedOwnerIntakeSourcePermissionResponse response; + + @Override + public void onNext(SelectedOwnerIntakeSourcePermissionResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + errorDescription = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..1bbcf2842f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java @@ -0,0 +1,199 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic owner-context tests; these do not establish TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeSourceReadService service = + new AccountSelectedOwnerIntakeSourceReadService(repository, registry, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCreatorRegistryReadOccursBetweenIndependentSqlReadbacks() { + var scope = scope("test"); + assertThat(scope.selected().requiredOwners()) + .doesNotContain(DraftCommitBinding.Owner.ENTITY_MANAGEMENT) + .doesNotContain(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + byte[] active = "exact-active-registry".getBytes(java.nio.charset.StandardCharsets.UTF_8); + var current = + new AccountSelectedOwnerIntakeSourceReservationRepository.SourceReadCurrentness( + "token-hash", + DraftAuthorizationFenceBinding.digest(active), + 1_900_000_000L, + "issuer-evidence", + "complete-source-vector"); + TransactionStatus status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.sourceReadCurrentness(scope)).thenReturn(current); + when(registry.readActive("token-hash")).thenReturn(active); + asPeer( + "test", + "game-design-service", + () -> service.readSourceScope(scope, scope.intendedReader(), scope.purpose())); + + InOrder order = inOrder(repository, registry); + order.verify(repository).sourceReadCurrentness(scope); + order.verify(registry).readActive("token-hash"); + order.verify(repository).readSourceScope(scope, current); + verify(transactions, times(2)).commit(status); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definition.capture()); + assertThat(definition.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(value.isReadOnly()).isFalse(); + }); + } + + @Test + void changedActiveRegistryDeniesBeforeFinalDatabaseConfirmation() { + var scope = scope("test"); + byte[] originalActive = "original-active".getBytes(java.nio.charset.StandardCharsets.UTF_8); + TransactionStatus status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.sourceReadCurrentness(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.SourceReadCurrentness( + "token-hash", + DraftAuthorizationFenceBinding.digest(originalActive), + 1_900_000_000L, + "issuer-evidence", + "complete-source-vector")); + when(registry.readActive("token-hash")).thenReturn("replaced-active".getBytes()); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asPeer( + "test", + "game-design-service", + () -> service.readSourceScope(scope, scope.intendedReader(), scope.purpose()))); + + verify(repository, never()).readSourceScope(any(), any()); + verify(transactions).commit(status); + } + + @Test + void authenticatesExactPeerAndRejectsEndUserContextBeforeScopeOrStorageAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.readSourceScope(null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", "game-design-service", () -> service.readSourceScope(null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "account-service", () -> service.readSourceScope(null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", "game-design-service", () -> service.readSourceScope(null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, registry, transactions); + } + + private static SelectedOwnerIntakeSourceReadScope scope(String namespace) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1L, "tenant-key", 2L, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + namespace, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + action.run(); + } finally { + peer.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java new file mode 100644 index 0000000000..5a3901a2ab --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +/** Synthetic transaction-bound repository boundary tests; no PostgreSQL proof is claimed. */ +class AccountSelectedOwnerIntakeSourceReservationRepositoryTest { + @Test + void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + assertThatThrownBy(() -> repository.reserveSourceRead(null, null, null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findSourceReadScope(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + + assertThatThrownBy(() -> repository.recoverSourceRead(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.abortSourceRead(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.sourceReadCurrentness(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readSourceScope(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + verifyNoInteractions(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java new file mode 100644 index 0000000000..105b642c97 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic owner producer tests; these do not establish TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReservationServiceTest { + private static final String TOKEN = "header.payload.signature"; + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeSourceReservationService service = + new AccountSelectedOwnerIntakeSourceReservationService( + actors, fences, repository, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void freshProducerRunsCurrentActorThenSelectedAdmissionBeforePersisting() { + var selected = selected(); + assertThat(selected.requiredOwners()) + .doesNotContain(DraftCommitBinding.Owner.ENTITY_MANAGEMENT) + .doesNotContain(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + UUID actorId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + var currentSource = source(actorId); + var actorCurrent = + new AccountControlUiActorService.Current( + stored(actorId, selected.target().canonicalTenantId()), + snapshot(List.of(currentSource))); + var environment = mock(CapturedEnvironmentBoundary.class); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + selected.requestId(), + actorId, + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + "test", + tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(actorCurrent), + eq("test"), + any(Runnable.class))) + .thenReturn(scope); + doAnswer( + invocation -> { + Function action = + invocation.getArgument(3); + return action.apply(actorCurrent); + }) + .when(actors) + .withCurrent(eq(TOKEN), eq(selected.target().canonicalTenantId()), eq(environment), any()); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.reserveSourceRead( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + environment)); + + assertThat(result).isEqualTo(scope); + InOrder order = inOrder(repository, actors, fences); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + "test", + tokenHash(TOKEN)); + order + .verify(actors) + .withCurrent(eq(TOKEN), eq(selected.target().canonicalTenantId()), eq(environment), any()); + order.verify(fences).requireSelectedOwnerIntakeAdmission(List.of(currentSource), selected); + order + .verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(actorCurrent), + eq("test"), + any(Runnable.class)); + } + + @Test + void historicalRecoveryAndAbortUseTheExactOriginalCredentialAndDoNotRenewIt() { + var selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + "test", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + UUID.fromString("88888888-8888-4888-8888-888888888888"), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN))) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + when(repository.abortSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED)); + + var recovered = + asPeerResult( + "test", + "game-design-service", + () -> + service.recover( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected)); + var aborted = + asPeerResult( + "test", + "game-design-service", + () -> + service.abortSourceRead( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected)); + + assertThat(recovered.state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + assertThat(aborted.state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + InOrder order = inOrder(repository); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN)); + order.verify(repository).recoverSourceRead(scope); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN)); + order.verify(repository).abortSourceRead(scope); + } + + @Test + void exactSameNamespaceGameDesignPeerIsRequiredBeforeInputsOrStorage() { + assertCode( + Status.Code.UNAUTHENTICATED, () -> service.reserveSourceRead(null, null, null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", + "game-design-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "account-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "game-design-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(actors, fences, repository, transactions); + } + + @Test + void originalCreatorRecoveryUsesAnIndependentReadCommittedTransaction() { + var selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + selected.requestId(), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + + asPeer("test", "game-design-service", () -> service.recover(scope)); + + var definition = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(repository).recoverSourceRead(scope); + } + + private static AccountControlUiAuthority.Snapshot snapshot( + List sources) { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.sources()).thenReturn(sources); + when(snapshot.issuanceFence()).thenReturn(17L); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 7))); + return snapshot; + } + + private static AccountControlUiIssuanceRepository.Stored stored(UUID actorId, UUID tenantId) { + Record row = mock(Record.class); + var operation = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + var sourcePayload = AccountControlUiAuthority.canonical(Map.of("sources", List.of("AQID"))); + var bundle = + AccountControlUiAuthority.canonical( + Map.of("issuanceFence", 17, "outboxCheckpoints", List.of())); + when(row.get("request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("operation_id", UUID.class)).thenReturn(operation); + when(row.get("token_jti", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("account_uuid", UUID.class)).thenReturn(actorId); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("caller_context_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("caller_workload", String.class)).thenReturn("game-design-service"); + when(row.get("request_mac_key_id", String.class)).thenReturn("key"); + when(row.get("request_digest", String.class)).thenReturn("digest"); + when(row.get("status", String.class)).thenReturn("COMMITTED"); + when(row.get("token_hash", String.class)).thenReturn(tokenHash(TOKEN)); + when(row.get("claims_payload", byte[].class)).thenReturn(new byte[] {1}); + when(row.get("source_payload", byte[].class)).thenReturn(sourcePayload); + when(row.get("bundle_payload", byte[].class)).thenReturn(bundle); + when(row.get("signer_receipt", byte[].class)).thenReturn(new byte[] {2}); + when(row.get("pending_registry", byte[].class)).thenReturn(new byte[] {3}); + when(row.get("active_registry", byte[].class)).thenReturn(new byte[] {4}); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(1_800_000_000L); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(1_800_000_300L); + when(row.get("recovery_expires_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.parse("2027-01-01T00:01:00Z")); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static DraftAuthorizationFenceBinding.SourceEvidence source(UUID actorId) { + return new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actorId.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + UUID version = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1L, "tenant-key", 2L, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + } + + private static String tokenHash(String value) { + return AccountControlUiIssuanceRepository.hash(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + action.run(); + } finally { + peer.detach(previous); + } + } + + private static T asPeerResult(String namespace, String workload, Supplier action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + return action.get(); + } finally { + peer.detach(previous); + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 065763d6e7..a9bdc9d9ff 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -222,6 +222,16 @@ public AccountGameLogicIntakeSourceReadService gameLogicIntakeSourceReadService( namespace); } + /** Actual preliminary permission owner; upstream creator/environment inputs remain controlled. */ + public AccountSelectedOwnerIntakeSourceReadService selectedOwnerIntakeSourceReadService( + String namespace) { + return new AccountSelectedOwnerIntakeSourceReadService( + new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), + coordination, + f.manager, + namespace); + } + /** * Real Account control-UI creator retained for composition with the original StartSession proof. */ diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 64efff1f0e..7910399321 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -134,9 +134,9 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { - if (migrationTarget != null && !"160.1".equals(migrationTarget)) { + if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention predecessor is supported"); + "Only the preserved 160.1 source-retention or 1006 source-disclosure frontier is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); @@ -548,7 +548,11 @@ private org.flywaydb.core.api.configuration.FluentConfiguration migrationConfigu .schemas(migrationSchema) .defaultSchema(migrationSchema) .placeholders(Map.of("serviceSchema", migrationSchema)) - .locations("filesystem:" + accountMigrations()); + .locations( + "filesystem:" + accountMigrations(), + "filesystem:" + accountMigrations() + .resolve("../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()); } private static Path accountMigrations() { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java new file mode 100644 index 0000000000..368673e629 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for preliminary selected-owner source-scope confirmation. */ +public final class GrpcSelectedOwnerIntakeSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub> + implements SelectedOwnerIntakeSourceReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account selected-owner read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-owner read stub unavailable"); + initialized = true; + } + + /** Returns Account's exact preliminary confirmation after authenticating its server identity. */ + @Override + public SelectedOwnerIntakeSourceReadEvidence read( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account selected-owner read must run outside SQL"); + Objects.requireNonNull(request, "source-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account selected-owner read must use the configured workload namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSourceScope(SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request)); + try { + return SelectedOwnerIntakeSourceReadProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid preliminary selected-owner source-read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account selected-owner read client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException("Account selected-owner read requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Account selected-owner read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-owner read requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account selected-owner read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account selected-owner read " + label + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java new file mode 100644 index 0000000000..00fa374152 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Dedicated Account confirmation of a preliminary selected-owner source-read scope. */ +public interface SelectedOwnerIntakeSourceReadClient { + SelectedOwnerIntakeSourceReadEvidence read(SelectedOwnerIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java new file mode 100644 index 0000000000..1d8b44177f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Preliminary Account confirmation of the exact Entity/Automation source-read scope. */ +public record SelectedOwnerIntakeSourceReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeSourceReadEvidence { + Objects.requireNonNull(request, "source-read request is required"); + } + + /** + * This request transports integrity input only; it does not assert finalized retention rights. + */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + String intendedReader, + String purpose, + SelectedOwnerIntakeSourceReadScope scope) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || scope == null) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if ((scope.owner() != Owner.ENTITY_MANAGEMENT && scope.owner() != Owner.AUTOMATION_SCRIPTING) + || !targetNamespace.equals(scope.targetNamespace()) + || !scope.intendedReader().equals(intendedReader) + || !scope.purpose().equals(purpose)) { + throw invalid(); + } + if (readRequestId.equals(scope.operationId()) + || readRequestId.equals(scope.fenceId()) + || readRequestId.equals(scope.intakeRequestId()) + || readRequestId.equals(scope.actorAccountId()) + || readRequestId.equals(scope.selected().requestId()) + || readRequestId.equals(scope.selected().commitId())) { + throw invalid(); + } + } + + public static Request create(String namespace, SelectedOwnerIntakeSourceReadScope scope) { + Objects.requireNonNull(scope, "source-read scope is required"); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (sameIdentity(readRequestId, scope)); + return new Request( + SCHEMA_VERSION, namespace, readRequestId, scope.intendedReader(), scope.purpose(), scope); + } + + private static boolean sameIdentity(UUID candidate, SelectedOwnerIntakeSourceReadScope scope) { + return candidate.equals(scope.operationId()) + || candidate.equals(scope.fenceId()) + || candidate.equals(scope.intakeRequestId()) + || candidate.equals(scope.actorAccountId()) + || candidate.equals(scope.selected().requestId()) + || candidate.equals(scope.selected().commitId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid preliminary selected-owner source-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java new file mode 100644 index 0000000000..f57d97132f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed preliminary source-scope wire mapping and exact Account echo validation. */ +public final class SelectedOwnerIntakeSourceReadProtoCodec { + public static final int MAX_WIRE_BYTES = 8 * 1024 * 1024; + + private SelectedOwnerIntakeSourceReadProtoCodec() {} + + public static SelectedOwnerIntakeSourcePermissionRequest toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + Objects.requireNonNull(request, "source-read request is required"); + var wire = + SelectedOwnerIntakeSourcePermissionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setPreliminarySourceScope(ByteString.copyFrom(request.scope().canonicalBytes())) + .setPreliminaryScopeDigest(request.scope().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeSourceReadEvidence.Request fromRequest( + SelectedOwnerIntakeSourcePermissionRequest request) { + requireKnownAndWithinBudget(request); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var scope = + SelectedOwnerIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray()); + if (!scope.digest().equals(request.getPreliminaryScopeDigest())) + throw invalid("Changed preliminary source-scope digest"); + return new SelectedOwnerIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + scope); + } + + public static SelectedOwnerIntakeSourcePermissionResponse toResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + var wire = + SelectedOwnerIntakeSourcePermissionResponse.newBuilder() + .setRequest(toRequest(request)) + .setPermitted(true) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeSourceReadEvidence fromResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourcePermissionResponse response) { + Objects.requireNonNull(request, "source-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getPermitted()) { + throw invalid("Exact permitted Account source-scope confirmation required"); + } + return new SelectedOwnerIntakeSourceReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner source-read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner source-read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner source-read message exceeds the 8 MiB wire budget"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java new file mode 100644 index 0000000000..c78a9a468a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +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.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Integrity input for a distinct preliminary Account source reservation. Decoding establishes no + * Account authentication, source completeness, or finalized owner retention permission. + */ +public record SelectedOwnerIntakeSourceReadScope( + Owner owner, + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + DraftCommitBinding selected) { + public static final int MAX_BYTES = 4194304; + + public SelectedOwnerIntakeSourceReadScope { + schemaFor(owner); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Canonical scope namespace required"); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(selected, "selected"); + encode(owner, targetNamespace, operationId, fenceId, intakeRequestId, actorAccountId, selected); + } + + public String schema() { + return schemaFor(owner); + } + + public String purpose() { + return purposeFor(owner); + } + + public String intendedReader() { + return accountReader(targetNamespace); + } + + public byte[] canonicalBytes() { + return encode( + owner, targetNamespace, operationId, fenceId, intakeRequestId, actorAccountId, selected); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static SelectedOwnerIntakeSourceReadScope fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Invalid owner source scope size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + String schema = reader.text(); + Owner owner = Owner.valueOf(reader.text()); + if (!schemaFor(owner).equals(schema)) + throw new IllegalArgumentException("Owner source scope schema differs"); + String namespace = reader.text(); + UUID operation = uuid(reader.text()); + UUID fence = uuid(reader.text()); + UUID request = uuid(reader.text()); + UUID actor = uuid(reader.text()); + var selected = DraftCommitBinding.fromStored(reader.text(), reader.text()); + var result = + new SelectedOwnerIntakeSourceReadScope( + owner, namespace, operation, fence, request, actor, selected); + reader.expect(result.intendedReader()); + reader.expect(result.purpose()); + reader.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical owner source scope"); + return result; + } + + private static byte[] encode( + Owner owner, + String namespace, + UUID operation, + UUID fence, + UUID request, + UUID actor, + DraftCommitBinding selected) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schemaFor(owner)); + DraftAuthorizationFenceBinding.frame(out, owner.name()); + DraftAuthorizationFenceBinding.frame(out, namespace); + for (var id : List.of(operation, fence, request, actor)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selected.digest()); + DraftAuthorizationFenceBinding.frame(out, accountReader(namespace)); + DraftAuthorizationFenceBinding.frame(out, purposeFor(owner)); + if (out.size() > MAX_BYTES) + throw new IllegalArgumentException("Owner source scope exceeds 4 MiB"); + return out.toByteArray(); + } + + private static String schemaFor(Owner owner) { + if (owner == Owner.ENTITY_MANAGEMENT) return "account-entity-intake-source-read/v1"; + if (owner == Owner.AUTOMATION_SCRIPTING) return "account-automation-intake-source-read/v1"; + throw new IllegalArgumentException("Unsupported selected source intake owner"); + } + + private static String purposeFor(Owner owner) { + schemaFor(owner); + return owner == Owner.ENTITY_MANAGEMENT ? "ENTITY_INTAKE_SOURCE" : "AUTOMATION_INTAKE_SOURCE"; + } + + private static String accountReader(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java new file mode 100644 index 0000000000..0804dcec58 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java @@ -0,0 +1,179 @@ +package net.firedevops.firemud.common.gamedesign; + +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; + +/** Branding selected source only; no total inventory or template completeness claim. */ +public record BrandingSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public BrandingSourceSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact branding asset source epoch and genesis required"); + items = List.copyOf(items); + new BrandingSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Branding asset items must be in canonical key order"); + } + + public record Item( + BrandingSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact branding asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role().name()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-branding-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "roles", + roleDeclarations(), + "items", + items.stream().map(Item::object).toList())); + } + + /** Every role is explicitly declared against actual genesis and selected writer history. */ + public Map roleDeclarations() { + var result = new java.util.TreeMap(); + for (var role : BrandingSource.Role.values()) + result.put( + role.name(), + items.stream().anyMatch(item -> item.reference().role() == role) ? "PRESENT" : "EMPTY"); + return Map.copyOf(result); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static BrandingSourceSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "roles", + "items"); + if (!"game-design-branding-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported branding asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!BrandingSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family"))) + throw new IllegalArgumentException("Unsupported branding source family or role"); + var reference = + new BrandingSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + BrandingSource.Role.valueOf(CommandSource.requiredStoredText(node, "role")), + BrandingSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new BrandingSourceSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical branding asset snapshot"); + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java new file mode 100644 index 0000000000..c83cce9605 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.gamedesign; + +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; + } + + 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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java index 127f48102d..9334aebf37 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java @@ -267,7 +267,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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java new file mode 100644 index 0000000000..4c86b7343f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for complete selected-owner source content. */ +public final class GrpcSelectedOwnerIntakeSourceClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub> + implements SelectedOwnerIntakeSourceClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Design source client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) throw new IllegalStateException("Game Design source stub unavailable"); + initialized = true; + } + + /** Reads exact selected source content after authenticating the configured Game Design peer. */ + @Override + public SelectedOwnerIntakeSourceContent read( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Game Design selected-owner source read must run outside SQL"); + Objects.requireNonNull(request, "selected-owner source-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Game Design selected-owner source read must use the configured workload namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSource(SelectedOwnerIntakeSourceProtoCodec.toRequest(request)); + try { + return SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid selected-owner source content", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignSelectedOwnerIntakeSourceServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Game Design selected-owner source client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException( + "Game Design selected-owner source requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Game Design selected-owner source requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Game Design selected-owner source requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design selected-owner source " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Game Design selected-owner source " + label + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java new file mode 100644 index 0000000000..29dfd28e51 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.gamedesign; + +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; + +/** Reads complete immutable selected-owner source content from Game Design. */ +public interface SelectedOwnerIntakeSourceClient { + SelectedOwnerIntakeSourceContent read(SelectedOwnerIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java new file mode 100644 index 0000000000..b6c06f57e4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** + * Exact six-family Game Design source content bound to one selected-owner preliminary scope. + * + *

Decoding checks framing, hashes, canonical JSON bindings and each existing typed source + * snapshot. It does not authenticate disclosure, grant finalization or retention authority, prove + * an owner inventory complete or empty, or create an owner receipt. Template snapshot v1/v2 parsing + * retains the stored grammar but does not prove a fresh authored inventory. Typed snapshot + * integrity is not independent proof that all owner references are resolved. + */ +public final class SelectedOwnerIntakeSourceContent { + public static final String DOMAIN = "game-design-selected-owner-intake-source/v1"; + public static final int MAX_BYTES = 8 * 1024 * 1024; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + private final SelectedOwnerIntakeSourceReadScope scope; + private final byte[] canonicalBytes; + private final String digest; + private final Map snapshots; + private final CommandSnapshot commandSource; + private final RealmPolicySnapshot realmPolicySource; + private final AssetSnapshot assetSource; + private final BrandingSourceSnapshot brandingSource; + private final GameplayRuleSelectedSource gameplaySource; + private final TemplateConfigSourceSnapshot templateConfigSource; + + private SelectedOwnerIntakeSourceContent( + SelectedOwnerIntakeSourceReadScope scope, + byte[] canonicalBytes, + String digest, + Map snapshots, + CommandSnapshot commandSource, + RealmPolicySnapshot realmPolicySource, + AssetSnapshot assetSource, + BrandingSourceSnapshot brandingSource, + GameplayRuleSelectedSource gameplaySource, + TemplateConfigSourceSnapshot templateConfigSource) { + this.scope = scope; + this.canonicalBytes = canonicalBytes.clone(); + this.digest = digest; + var copiedSnapshots = new LinkedHashMap(); + for (String family : FAMILIES) copiedSnapshots.put(family, snapshots.get(family).clone()); + this.snapshots = Map.copyOf(copiedSnapshots); + this.commandSource = commandSource; + this.realmPolicySource = realmPolicySource; + this.assetSource = assetSource; + this.brandingSource = brandingSource; + this.gameplaySource = gameplaySource; + this.templateConfigSource = templateConfigSource; + } + + /** + * Decodes exact persisted content against the independently expected preliminary scope and + * content digest. This value is integrity evidence only; it is not an authority grant. + */ + public static SelectedOwnerIntakeSourceContent fromStored( + byte[] bytes, SelectedOwnerIntakeSourceReadScope expectedScope, String expectedDigest) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Selected owner source content size is invalid"); + Objects.requireNonNull(expectedScope, "expectedScope"); + if (expectedDigest == null || !SHA256.matcher(expectedDigest).matches()) + throw new IllegalArgumentException("Expected selected owner source digest is invalid"); + + // Enforce the envelope budget before copying, hashing or parsing any caller-controlled bytes. + byte[] stored = bytes.clone(); + String actualDigest = DraftAuthorizationFenceBinding.digest(stored); + if (!actualDigest.equals(expectedDigest)) + throw new IllegalArgumentException("Selected owner source content digest differs"); + + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + byte[] scopeBytes = reader.bytes(); + String scopeDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(scopeBytes).equals(scopeDigest)) + throw new IllegalArgumentException("Selected owner source scope digest differs"); + SelectedOwnerIntakeSourceReadScope decodedScope = + SelectedOwnerIntakeSourceReadScope.fromStored(scopeBytes); + if (!Arrays.equals(scopeBytes, decodedScope.canonicalBytes()) + || !decodedScope.equals(expectedScope) + || decodedScope.owner() != expectedScope.owner() + || !decodedScope.selected().equals(expectedScope.selected()) + || !decodedScope.digest().equals(scopeDigest)) + throw new IllegalArgumentException("Selected owner source scope differs from expectation"); + + var snapshots = new LinkedHashMap(); + for (String family : FAMILIES) { + reader.expect(family); + byte[] snapshot = reader.bytes(); + if (snapshot.length == 0) + throw new IllegalArgumentException("Selected " + family + " snapshot size is invalid"); + String familyDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(snapshot).equals(familyDigest)) + throw new IllegalArgumentException("Selected " + family + " snapshot digest differs"); + requireSelectedBinding(family, snapshot, decodedScope.selected()); + snapshots.put(family, snapshot); + } + reader.requireEnd(); + + CommandSnapshot commandSource = + CommandSnapshot.fromStored(utf8(snapshots.get("COMMAND"), "COMMAND")); + RealmPolicySnapshot realmPolicySource = + RealmPolicySnapshot.fromStored(utf8(snapshots.get("REALM_POLICY"), "REALM_POLICY")); + AssetSnapshot assetSource = AssetSnapshot.fromStored(utf8(snapshots.get("ASSET"), "ASSET")); + BrandingSourceSnapshot brandingSource = + BrandingSourceSnapshot.fromStored(utf8(snapshots.get("BRANDING"), "BRANDING")); + requireClosedGameDesignRevisions(decodedScope.selected()); + + GameplayRuleSelectedSource gameplaySource = + new GameplayRuleSelectedSource(utf8(snapshots.get("GAMEPLAY_RULE"), "GAMEPLAY_RULE")); + if (!decodedScope.selected().equals(gameplaySource.binding())) + throw new IllegalArgumentException("Selected gameplay rule binding differs"); + + TemplateConfigSourceSnapshot templateConfigSource = + TemplateConfigSourceSnapshot.fromStored( + utf8(snapshots.get("TEMPLATE_CONFIG"), "TEMPLATE_CONFIG")); + if (!decodedScope.selected().equals(templateConfigSource.binding())) + throw new IllegalArgumentException("Selected template config binding differs"); + + return new SelectedOwnerIntakeSourceContent( + decodedScope, + stored, + actualDigest, + snapshots, + commandSource, + realmPolicySource, + assetSource, + brandingSource, + gameplaySource, + templateConfigSource); + } + + public SelectedOwnerIntakeSourceReadScope scope() { + return scope; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + /** Returns the original canonical snapshot bytes for one of the six closed family names. */ + public byte[] snapshotBytes(String closedFamily) { + if (closedFamily == null) + throw new IllegalArgumentException("Unsupported selected owner source family"); + byte[] snapshot = snapshots.get(closedFamily); + if (snapshot == null) + throw new IllegalArgumentException("Unsupported selected owner source family"); + return snapshot.clone(); + } + + public GameplayRuleSelectedSource gameplaySource() { + return gameplaySource; + } + + public CommandSnapshot commandSource() { + return commandSource; + } + + public RealmPolicySnapshot realmPolicySource() { + return realmPolicySource; + } + + public AssetSnapshot assetSource() { + return assetSource; + } + + public BrandingSourceSnapshot brandingSource() { + return brandingSource; + } + + public TemplateConfigSourceSnapshot templateConfigSource() { + return templateConfigSource; + } + + private static void requireClosedGameDesignRevisions(DraftCommitBinding binding) { + // Each actual owner grammar validates its family and rejects unrecognized Game Design kinds. + // Other owners' payloads are not interpreted as Game Design sources or silently reconstructed. + CommandSource.mutations(binding); + AssetSource.mutations(binding); + BrandingSource.mutations(binding); + GameplayRuleSource.mutations(binding); + TemplateConfigSourceValues.mutations(binding); + for (var revision : binding.revisions()) { + if (revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(revision)) { + RealmPolicySource.revision(binding, revision); + } + } + } + + private static void requireSelectedBinding( + String family, byte[] snapshot, DraftCommitBinding selected) { + String json = utf8(snapshot, family); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!Arrays.equals(snapshot, canonical)) + throw new IllegalArgumentException( + "Selected " + family + " snapshot is not canonical JSON"); + var root = GameplayRuleManifest.tree(json); + if (!root.isObject()) + throw new IllegalArgumentException( + "Selected " + family + " snapshot root must be an object"); + var bindingJson = root.get("bindingJson"); + var bindingDigest = root.get("bindingDigest"); + if (bindingJson == null + || !bindingJson.isTextual() + || bindingDigest == null + || !bindingDigest.isTextual()) + throw new IllegalArgumentException("Selected " + family + " binding fields must be text"); + DraftCommitBinding decoded = + DraftCommitBinding.fromStored(bindingJson.textValue(), bindingDigest.textValue()); + if (!selected.equals(decoded)) + throw new IllegalArgumentException("Selected " + family + " binding differs"); + } catch (IOException failure) { + throw new IllegalArgumentException( + "Selected " + family + " snapshot JSON is invalid", failure); + } + } + + private static String utf8(byte[] bytes, String family) { + String value = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, value.getBytes(StandardCharsets.UTF_8))) + throw new IllegalArgumentException("Selected " + family + " snapshot is not exact UTF-8"); + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java new file mode 100644 index 0000000000..c0f213858a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; + +/** Closed wire mapping for selected-owner source content and exact request-echo validation. */ +public final class SelectedOwnerIntakeSourceProtoCodec { + public static final int MAX_WIRE_BYTES = 16 * 1024 * 1024; + + private SelectedOwnerIntakeSourceProtoCodec() {} + + public static SelectedOwnerIntakeSourceRequest toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + var wire = + SelectedOwnerIntakeSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setPreliminarySourceScope(ByteString.copyFrom(request.scope().canonicalBytes())) + .setPreliminaryScopeDigest(request.scope().digest()) + .build(); + requireWithinBudget(wire); + return wire; + } + + /** Decodes integrity metadata only; this does not authenticate or authorize source disclosure. */ + public static SelectedOwnerIntakeSourceReadEvidence.Request fromRequest( + SelectedOwnerIntakeSourceRequest request) { + requireKnownAndWithinBudget(request, "selected-owner source-read request"); + try { + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var scope = + SelectedOwnerIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray()); + if (!scope.digest().equals(request.getPreliminaryScopeDigest())) + throw invalid("Changed preliminary source-scope digest"); + return new SelectedOwnerIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + scope); + } catch (IllegalArgumentException exception) { + throw invalid("Invalid selected-owner source-read request", exception); + } + } + + public static SelectedOwnerIntakeSourceResponse toResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceContent content) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + Objects.requireNonNull(content, "selected-owner source content is required"); + if (!request.scope().equals(content.scope())) + throw invalid("Selected source content is bound to a different preliminary scope"); + var checkedContent = + SelectedOwnerIntakeSourceContent.fromStored( + content.canonicalBytes(), request.scope(), content.digest()); + var wire = + SelectedOwnerIntakeSourceResponse.newBuilder() + .setRequest(toRequest(request)) + .setSelectedSourceContent(ByteString.copyFrom(checkedContent.canonicalBytes())) + .setSelectedSourceDigest(checkedContent.digest()) + .build(); + requireWithinBudget(wire); + return wire; + } + + /** Validates the complete unchanged echo before accepting bound source content. */ + public static SelectedOwnerIntakeSourceContent fromResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceResponse response) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + requireKnownAndWithinBudget(response, "selected-owner source-read response"); + if (!response.hasRequest()) throw invalid("Selected-owner response has no request echo"); + var echoedRequest = response.getRequest(); + requireKnownAndWithinBudget(echoedRequest, "selected-owner response request echo"); + if (!toRequest(request).equals(echoedRequest)) + throw invalid("Selected-owner response does not echo the complete request unchanged"); + + var contentBytes = response.getSelectedSourceContent(); + if (contentBytes.isEmpty() || contentBytes.size() > SelectedOwnerIntakeSourceContent.MAX_BYTES) + throw invalid("Missing or oversized selected-owner source content"); + try { + return SelectedOwnerIntakeSourceContent.fromStored( + contentBytes.toByteArray(), request.scope(), response.getSelectedSourceDigest()); + } catch (IllegalArgumentException exception) { + throw invalid("Game Design returned invalid selected-owner source content", exception); + } + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized " + label); + if (!wire.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown fields in " + label); + } + + private static void requireWithinBudget(Message wire) { + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Selected-owner source message exceeds the 16 MiB wire budget"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java new file mode 100644 index 0000000000..4ae118be72 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -0,0 +1,276 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; + +/** Lifecycle proof with real file watchers and a mocked channel factory, not a TLS handshake. */ +class SelectedOwnerIntakeClientLifecycleTest { + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @ParameterizedTest + @EnumSource(ClientKind.class) + @Timeout(15) + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void closeReleasesClientMonitorBeforeDrainingCertificateCallback( + ClientKind kind, @TempDir Path directory) + throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + CountDownLatch releaseClientMonitor = new CountDownLatch(1); + AtomicReference closeFailure = new AtomicReference<>(); + Thread monitorHolder = null; + Thread closeThread = null; + AbstractReloadingBlockingGrpcClient client = null; + TlsCertificateWatcher originalWatcher = null; + List channels = new CopyOnWriteArrayList<>(); + try { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + CommonGrpcClientProperties tls = tls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenAnswer( + invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); + ClientHandle handle = kind.create(endpoints, tls, channelFactory); + client = handle.client(); + handle.initialize().run(); + AbstractReloadingBlockingGrpcClient clientUnderTest = client; + + originalWatcher = watcher(client); + Set activeCallbacks = activeCallbacks(originalWatcher); + TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); + TlsCertificateWatcher delegatedWatcher = originalWatcher; + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(clientUnderTest)) + .as("the client monitor must be released before watcher shutdown") + .isFalse(); + delegatedWatcher.close(); + return null; + }) + .when(closeBoundary) + .close(); + setWatcher(clientUnderTest, closeBoundary); + CountDownLatch clientMonitorHeld = new CountDownLatch(1); + monitorHolder = + new Thread( + () -> { + synchronized (clientUnderTest) { + clientMonitorHeld.countDown(); + awaitLatch(releaseClientMonitor); + } + }, + "selected-owner-intake-client-monitor-holder"); + monitorHolder.start(); + assertThat(clientMonitorHeld.await(5, TimeUnit.SECONDS)).isTrue(); + + CountDownLatch closeStarted = new CountDownLatch(1); + Thread closeWorker = + new Thread( + () -> { + closeStarted.countDown(); + try { + clientUnderTest.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } + }, + "selected-owner-intake-client-close"); + closeThread = closeWorker; + closeWorker.start(); + assertThat(closeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); + + Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); + Thread callback = awaitBlockedReloadCallback(activeCallbacks); + assertThat(callback).isNotNull(); + + releaseClientMonitor.countDown(); + closeWorker.join(TimeUnit.SECONDS.toMillis(4)); + assertThat(closeWorker.isAlive()) + .as("close must not hold the client monitor while the watcher drains its callback") + .isFalse(); + assertThat(closeFailure.get()).isNull(); + + clientUnderTest.close(); + assertThatThrownBy(() -> handle.initialize().run()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThat(channels).isNotEmpty(); + for (ManagedChannel channel : channels) { + verify(channel, times(1)).shutdown(); + } + } finally { + releaseClientMonitor.countDown(); + if (monitorHolder != null) { + monitorHolder.join(TimeUnit.SECONDS.toMillis(5)); + } + if (closeThread != null) { + closeThread.join(TimeUnit.SECONDS.toMillis(7)); + } + try { + if (originalWatcher != null) { + originalWatcher.close(); + } + } finally { + try { + if (client != null) { + if (originalWatcher != null) { + setWatcher(client, originalWatcher); + } + client.close(); + } + } finally { + restoreReloadPolicy(previousReloadPolicy); + } + } + } + } + + @FunctionalInterface + private interface Initialize { + void run() throws Exception; + } + + private record ClientHandle(AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} + + private enum ClientKind { + SOURCE_READ, + GAME_DESIGN_SOURCE; + + ClientHandle create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory) { + return switch (this) { + + + case SOURCE_READ -> { + var client = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + + case GAME_DESIGN_SOURCE -> { + var client = new GrpcSelectedOwnerIntakeSourceClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + + }; + } + } + + private static Thread awaitBlockedReloadCallback(Set activeCallbacks) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + for (Thread callback : activeCallbacks) { + if (callback.getState() == Thread.State.BLOCKED + && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { + return callback; + } + } + Thread.sleep(10); + } + return null; + } + + private static boolean hasFrame(Thread thread, String className, String methodName) { + for (StackTraceElement frame : thread.getStackTrace()) { + if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!condition.getAsBoolean() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertThat(condition.getAsBoolean()).isTrue(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + + private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + return (TlsCertificateWatcher) field.get(client); + } + + private static void setWatcher( + AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + field.set(client, watcher); + } + + @SuppressWarnings("unchecked") + private static Set activeCallbacks(TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); + field.setAccessible(true); + return (Set) field.get(watcher); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static void restoreReloadPolicy(String previousValue) { + if (previousValue == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousValue); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java new file mode 100644 index 0000000000..3ce2d53d90 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java @@ -0,0 +1,529 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic scopes exercise client mTLS and correlation, not Account database/source proof. */ +class SelectedOwnerIntakeSourceReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private Server server; + private boolean stall; + private boolean substitute; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void pinsAccountServerAndRoundTripsBothPreliminaryOwnerScopes() throws Exception { + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + for (var owner : + List.of( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING)) { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(owner, NAMESPACE)); + assertThat(client.read(request).request()).isEqualTo(request); + } + assertThat(calls).hasValue(2); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.wrongServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE)); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(2); + } + } + + @Test + void transportsNearFourMiBCanonicalScopeAndEchoWithinEightMiBWireBudget() throws Exception { + var scope = scopeAtCanonicalLimit(); + assertThat(scope.canonicalBytes().length) + .isGreaterThan(SelectedOwnerIntakeSourceReadScope.MAX_BYTES - 16) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceReadScope.MAX_BYTES); + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); + + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThat(client.read(request).request()).isEqualTo(request); + } + } + + @Test + void rejectsOtherNamespaceAmbientSqlAndSubstitutedResponse() throws Exception { + start(pki.accountServer()); + substitute = true; + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var otherNamespace = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + "other", scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, "other")); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE)); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void boundsUnavailableAccountReadByFiveSecondDeadline() throws Exception { + stall = true; + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, NAMESPACE)); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresTlsAndReadableFileBackedCredentials() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceImplBase() { + @Override + public void readSourceScope( + SelectedOwnerIntakeSourcePermissionRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + if (!GAME_DESIGN_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) return; + var request = SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(wire); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + if (substitute) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcSelectedOwnerIntakeSourceReadClient newClient(TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + DraftCommitBinding.Owner owner, String namespace) { + return scope(owner, namespace, "{}"); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + DraftCommitBinding.Owner owner, String namespace, String revisionPayload) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 1L, + "tenant-key", + 2L, + "tenant-key", + "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + revisionPayload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static SelectedOwnerIntakeSourceReadScope scopeAtCanonicalLimit() { + int lower = 0; + int upper = SelectedOwnerIntakeSourceReadScope.MAX_BYTES; + while (lower < upper) { + int candidate = lower + (upper - lower + 1) / 2; + try { + scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE, "x".repeat(candidate)); + lower = candidate; + } catch (IllegalArgumentException tooLarge) { + upper = candidate - 1; + } + } + return scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE, "x".repeat(lower)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongServer, + TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-owner-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected-owner test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-owner-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("selected-owner-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java new file mode 100644 index 0000000000..0366f41ff1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic canonical scopes exercise the wire boundary, not Account or owner-source proof. */ +class SelectedOwnerIntakeSourceReadProtoCodecTest { + private static final String NAMESPACE = "test"; + + @Test + void roundTripsEntityAndAutomationScopesWithIndependentCorrelationsAndExactEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope(owner)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(wire)).isEqualTo(request); + assertThat(wire.getPreliminaryScopeDigest()).isEqualTo(request.scope().digest()); + assertThat(request.readRequestId()) + .isNotIn( + request.scope().operationId(), + request.scope().fenceId(), + request.scope().intakeRequestId(), + request.scope().actorAccountId(), + request.scope().selected().requestId(), + request.scope().selected().commitId()); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.fromResponse(request, response).request()) + .isEqualTo(request); + } + } + + @Test + void rejectsUnsupportedSchemaWrongDomainNamespaceReaderPurposeAndCorrelation() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.ENTITY_MANAGEMENT)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setTargetNamespace("other").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("AUTOMATION_INTAKE_SOURCE").build())) + .isInstanceOf(IllegalArgumentException.class); + for (UUID reusedIdentity : + List.of( + request.scope().operationId(), + request.scope().fenceId(), + request.scope().intakeRequestId(), + request.scope().actorAccountId(), + request.scope().selected().requestId(), + request.scope().selected().commitId())) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setReadRequestId(reusedIdentity.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingUnknownOversizedAndDigestSubstitutedRequests() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.AUTOMATION_SCRIPTING)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearPreliminarySourceScope().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPurpose( + "x".repeat(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresACompletePermittedAndUnmodifiedResponseEcho() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.ENTITY_MANAGEMENT)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + var oversizedResponseUnknownFields = + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder().setUnknownFields(oversizedResponseUnknownFields).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope(Owner owner) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 1L, + "tenant-key", + 2L, + "tenant-key", + "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java new file mode 100644 index 0000000000..534f448d55 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Stipulated immutable fixtures prove integrity only, never genuine Account or owner authority. */ +class SelectedOwnerIntakeSourceReadScopeTest { + private static final UUID TENANT = id(1); + private static final UUID VERSION = id(2); + private static final UUID OPERATION = id(3); + private static final UUID FENCE = id(4); + private static final UUID INTAKE = id(5); + private static final UUID ACTOR = id(6); + private static final UUID REQUEST = id(7); + private static final UUID COMMIT = id(8); + private static final UUID REVISION = id(9); + private static final String PAYLOAD = "{\"originalRevision\":\"retained exactly\"}"; + + @Test + void frozenDirectPreimageAndDigestRoundTripBothOwnerDomains() throws Exception { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner); + String schema = + owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-source-read/v1" + : "account-automation-intake-source-read/v1"; + String purpose = + owner == Owner.ENTITY_MANAGEMENT ? "ENTITY_INTAKE_SOURCE" : "AUTOMATION_INTAKE_SOURCE"; + // Independent, fixed-field preimage: no production scope encoder or framing helper. + byte[] expected = + frames( + schema, + owner.name(), + "test", + OPERATION.toString(), + FENCE.toString(), + INTAKE.toString(), + ACTOR.toString(), + frozenSelectedJson(), + digest(frozenSelectedJson().getBytes(StandardCharsets.UTF_8)), + "spiffe://firemud/ns/test/sa/account-service", + purpose); + assertThat(scope.selected().canonicalJson()).isEqualTo(frozenSelectedJson()); + assertThat(scope.canonicalBytes()).isEqualTo(expected); + assertThat(scope.digest()).isEqualTo(digest(expected)); + var restored = SelectedOwnerIntakeSourceReadScope.fromStored(expected); + assertThat(restored).isEqualTo(scope); + assertThat(restored.canonicalBytes()).isEqualTo(expected); + assertThat(restored.schema()).isEqualTo(schema); + assertThat(restored.purpose()).isEqualTo(purpose); + assertThat(restored.intendedReader()) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + } + } + + @Test + void everyIdentityAndTheCompleteSelectedBindingAffectIntegrity() { + var original = scope(Owner.ENTITY_MANAGEMENT); + var selected = original.selected(); + for (var changed : + List.of( + scope(Owner.AUTOMATION_SCRIPTING), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "other", OPERATION, FENCE, INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", id(10), FENCE, INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, id(10), INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, FENCE, id(10), ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, FENCE, INTAKE, id(10), selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(id(10), COMMIT, PAYLOAD)), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(REQUEST, id(10), PAYLOAD)), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(REQUEST, COMMIT, PAYLOAD + " ")))) { + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat(SelectedOwnerIntakeSourceReadScope.fromStored(changed.canonicalBytes())) + .isEqualTo(changed); + } + } + + @Test + void preservesEntireOriginalRevisionAndBaseWithoutInventingWorldAssociation() { + var original = scope(Owner.ENTITY_MANAGEMENT); + var decoded = SelectedOwnerIntakeSourceReadScope.fromStored(original.canonicalBytes()); + assertThat(decoded.selected()).isEqualTo(original.selected()); + assertThat(decoded.selected().baseCommitId()).isEqualTo("base-commit-0"); + assertThat(decoded.selected().revisions()) + .containsExactly( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, PAYLOAD)); + assertThat(decoded.selected().requiredOwners()) + .containsExactly(Owner.GAME_DESIGN_CONTROL_PLANE); + } + + @Test + void deniesUnknownOwnersAndCrossOwnerSchemaPurposeOrReader() throws Exception { + var scope = scope(Owner.ENTITY_MANAGEMENT); + for (Owner owner : + List.of(Owner.WORLD_MANAGEMENT, Owner.GAME_LOGIC, Owner.GAME_DESIGN_CONTROL_PLANE)) + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, scope.selected())) + .isInstanceOf(IllegalArgumentException.class); + for (String[] changed : + List.of( + new String[] { + "account-automation-intake-source-read/v1", + "ENTITY_MANAGEMENT", + "ENTITY_INTAKE_SOURCE", + scope.intendedReader() + }, + new String[] { + scope.schema(), "AUTOMATION_SCRIPTING", scope.purpose(), scope.intendedReader() + }, + new String[] {scope.schema(), "UNKNOWN", scope.purpose(), scope.intendedReader()}, + new String[] { + "account-entity-intake-source-read/v2", + "ENTITY_MANAGEMENT", + scope.purpose(), + scope.intendedReader() + }, + new String[] { + scope.schema(), "GAME_LOGIC", "GAME_LOGIC_INTAKE_SOURCE", scope.intendedReader() + }, + new String[] { + "account-game-logic-intake-source-read/v1", + "ENTITY_MANAGEMENT", + scope.purpose(), + scope.intendedReader() + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + "AUTOMATION_INTAKE_SOURCE", + scope.intendedReader() + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + scope.purpose(), + "spiffe://firemud/ns/test/sa/entity-management-service" + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + scope.purpose(), + "spiffe://firemud/ns/other/sa/account-service" + })) { + byte[] bytes = + wire( + changed[0], + changed[1], + "test", + ACTOR.toString(), + scope.selected().canonicalJson(), + scope.selected().digest(), + changed[3], + changed[2]); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void deniesMalformedTruncatedTrailingOversizedAndNoncanonicalInput() throws Exception { + var scope = scope(Owner.ENTITY_MANAGEMENT); + byte[] bytes = scope.canonicalBytes(); + byte[] invalidUtf8 = bytes.clone(); + invalidUtf8[4] = (byte) 0xc0; + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {-1, -1, -1, -1}, + invalidUtf8, + Arrays.copyOf(bytes, bytes.length - 1), + Arrays.copyOf(bytes, bytes.length + 1), + new byte[SelectedOwnerIntakeSourceReadScope.MAX_BYTES + 1])) + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + for (String actor : + List.of("00000000-0000-0000-0000-000000000000", "1-1-1-1-1", "NOT-A-UUID")) { + byte[] invalid = + wire( + scope.schema(), + scope.owner().name(), + "test", + actor, + scope.selected().canonicalJson(), + scope.selected().digest(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String namespace : List.of("Test", "test/other", " test", "")) { + byte[] invalid = + wire( + scope.schema(), + scope.owner().name(), + namespace, + ACTOR.toString(), + scope.selected().canonicalJson(), + scope.selected().digest(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + byte[] wrongDigest = + wire( + scope.schema(), + scope.owner().name(), + "test", + ACTOR.toString(), + scope.selected().canonicalJson(), + "sha256:" + "0".repeat(64), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(wrongDigest)) + .isInstanceOf(RuntimeException.class); + String noncanonical = " " + scope.selected().canonicalJson(); + byte[] padded = + wire( + scope.schema(), + scope.owner().name(), + "test", + ACTOR.toString(), + noncanonical, + digest(noncanonical.getBytes(StandardCharsets.UTF_8)), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(padded)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + scope.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding( + REQUEST, COMMIT, "x".repeat(SelectedOwnerIntakeSourceReadScope.MAX_BYTES)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNilReservationIdentitiesAndUnsupportedNullOwner() { + var selected = scope(Owner.ENTITY_MANAGEMENT).selected(); + UUID nil = new UUID(0, 0); + for (var ids : + List.of( + List.of(nil, FENCE, INTAKE, ACTOR), + List.of(OPERATION, nil, INTAKE, ACTOR), + List.of(OPERATION, FENCE, nil, ACTOR), + List.of(OPERATION, FENCE, INTAKE, nil))) + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + "test", + ids.get(0), + ids.get(1), + ids.get(2), + ids.get(3), + selected)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + null, "test", OPERATION, FENCE, INTAKE, ACTOR, selected)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope(Owner owner) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, binding(REQUEST, COMMIT, PAYLOAD)); + } + + private static DraftCommitBinding binding(UUID request, UUID commit, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + request, + commit, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static String frozenSelectedJson() { + return "{\"affectedUnits\":[{\"aggregateId\":\"" + + VERSION + + "\",\"aggregateType\":\"TEMPLATE_CONFIG\",\"expectedEpoch\":\"0\"," + + "\"owner\":\"GAME_DESIGN_CONTROL_PLANE\",\"scopeId\":\"ALL\"," + + "\"scopeType\":\"TEMPLATE_CONFIG\"}],\"baseCommitId\":\"base-commit-0\"," + + "\"canonicalTenantId\":\"" + + TENANT + + "\",\"canonicalVersionId\":\"" + + VERSION + + "\",\"commitId\":\"" + + COMMIT + + "\",\"requestId\":\"" + + REQUEST + + "\",\"requiredOwners\":[\"GAME_DESIGN_CONTROL_PLANE\"]," + + "\"revisions\":[{\"owner\":\"GAME_DESIGN_CONTROL_PLANE\"," + + "\"payload\":\"{\\\"originalRevision\\\":\\\"retained exactly\\\"}\",\"revisionId\":\"" + + REVISION + + "\",\"revisionOrder\":\"0\"}],\"schemaVersion\":\"1\"," + + "\"target\":{\"gameDesignVersionRowId\":\"23\",\"gameDesignVersionTenantKey\":\"tenant\"," + + "\"sourceGameRowId\":\"42\",\"sourceGameTenantKey\":\"tenant\"," + + "\"sourceProvenanceKind\":\"NEW_GAME_ROW\"}}"; + } + + private static byte[] wire( + String schema, + String owner, + String namespace, + String actor, + String selected, + String selectedDigest, + String reader, + String purpose) + throws Exception { + return frames( + schema, + owner, + namespace, + OPERATION.toString(), + FENCE.toString(), + INTAKE.toString(), + actor, + selected, + selectedDigest, + reader, + purpose); + } + + private static byte[] frames(String... fields) throws Exception { + var output = new ByteArrayOutputStream(); + var data = new DataOutputStream(output); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + data.writeInt(bytes.length); + data.write(bytes); + } + return output.toByteArray(); + } + + private static String digest(byte[] bytes) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID id(int value) { + return UUID.fromString("00000000-0000-4000-8000-" + String.format("%012d", value)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java index 465b31dad8..93a0281514 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java @@ -38,6 +38,49 @@ void rejectsTextAndFloatingPointDefinitionSchemaVersions() { } } + @Test + void explicitDeleteRequiresAnExistingEffectiveCommandKey() { + UUID commit = id("delete-commit"); + var inherited = + List.of( + new CommandSource.Definition( + "LOOK", commandDefinition("1"), id("prior-commit"), id("prior-revision"), "0")); + var delete = + new CommandSource.Mutation( + "0", id("delete-revision"), commit, CommandSource.OperationKind.DELETE, "look", null); + + assertThat(CommandSource.replay(inherited, List.of(delete))).isEmpty(); + assertThatThrownBy( + () -> + CommandSource.replay( + inherited, + List.of( + delete, + new CommandSource.Mutation( + "1", + id("second-delete-revision"), + commit, + CommandSource.OperationKind.DELETE, + "LOOK", + null)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + assertThatThrownBy( + () -> + CommandSource.replay( + List.of(), + List.of( + new CommandSource.Mutation( + "0", + id("absent-delete-revision"), + commit, + CommandSource.OperationKind.DELETE, + "absent", + null)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot delete an absent command definition key"); + } + private static DraftCommitBinding binding(String definitionJson) { String payload = CommandSource.canonical( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java new file mode 100644 index 0000000000..a525c43a3f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java @@ -0,0 +1,673 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic loopback transport proof; it does not establish genuine Game Design source reads. */ +class SelectedOwnerIntakeSourceClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String OTHER_CLIENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicInteger responseBytes = new AtomicInteger(); + private Server server; + private boolean stall; + private boolean substituteEcho; + private boolean largeResponse; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = + request(owner, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + assertThat(client.read(request).scope()).isEqualTo(request.scope()); + } + assertThat(calls).hasValue(2); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.wrongServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(2); + } + } + + @Test + void transportsLargeCompleteContentWithinExplicitWireBudget() throws Exception { + largeResponse = true; + start(pki.gameDesignServer()); + var request = + request( + Owner.AUTOMATION_SCRIPTING, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var content = client.read(request); + assertThat(content.scope()).isEqualTo(request.scope()); + assertThat(content.snapshotBytes("COMMAND").length).isGreaterThan(6_000_000); + assertThat(responseBytes.get()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES); + assertThat(calls).hasValue(1); + } + } + + @Test + void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() + throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.wrongClient())) { + client.init(); + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(1); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.expiredGameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(1); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.gameDesignServer()); + try (var client = newClient(pki.expiredGameDesignClient())) { + client.init(); + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void rejectsOtherNamespaceAmbientSqlSynchronizationAndSubstitutedEcho() throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var otherNamespace = + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload(), + "other"); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + + var request = + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + + substituteEcho = true; + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void boundsUnavailableReadByFiveSecondDeadline() throws Exception { + stall = true; + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy( + () -> + client.read( + request( + Owner.AUTOMATION_SCRIPTING, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresTlsAndReadableFileBackedCredentials() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + + var classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey("/tmp/client.key"); + classpath.setCaCert("/tmp/ca.crt"); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, classpath, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceImplBase() { + @Override + public void readSelectedSource( + SelectedOwnerIntakeSourceRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + if (peer == null || !GAME_DESIGN_URI.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) return; + var request = SelectedOwnerIntakeSourceProtoCodec.fromRequest(wire); + var content = content(request.scope(), largeResponse ? 6_500_000 : 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + responseBytes.set(response.getSerializedSize()); + if (substituteEcho) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcSelectedOwnerIntakeSourceClient newClient(TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new GrpcSelectedOwnerIntakeSourceClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, String payload) { + return request(owner, payload, NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, String payload, String namespace) { + return SelectedOwnerIntakeSourceReadEvidence.Request.create( + namespace, scope(owner, payload, namespace)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, String payload, String namespace) { + DraftCommitBinding selected = binding(COMMIT, payload); + return new SelectedOwnerIntakeSourceReadScope( + owner, namespace, OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, int largeCommandMarkerSize) { + var selected = scope.selected(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : FAMILIES) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> + SelectedOwnerIntakeSourceTestFixtures.snapshot( + family, selected, family.equals("COMMAND") ? largeCommandMarkerSize : 0); + }; + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] encoded = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); + } + + private static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST_ID, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameDesignServer, + TestIdentity wrongServer, + TestIdentity expiredGameDesignServer, + TestIdentity gameDesignClient, + TestIdentity wrongClient, + TestIdentity expiredGameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-content-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected-content test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-content-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity( + directory, caStore, caFile, "game-design-server", GAME_DESIGN_URI, true, false), + issueIdentity(directory, caStore, caFile, "wrong-server", ACCOUNT_URI, true, false), + issueIdentity(directory, caStore, caFile, "expired-server", GAME_DESIGN_URI, true, true), + issueIdentity( + directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false, false), + issueIdentity(directory, caStore, caFile, "wrong-client", OTHER_CLIENT_URI, false, false), + issueIdentity( + directory, caStore, caFile, "expired-client", GAME_DESIGN_URI, false, true)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("selected-content-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("selected-content-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("selected-content-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caFile, + String alias, + String workloadUri, + boolean server, + boolean expired) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + var startDate = expired ? List.of("-startdate", "2000/01/01 00:00:00") : List.of(); + var validity = expired ? "1" : "30"; + var generate = + new ArrayList( + List.of( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + validity, + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD)); + runKeytool(generate.toArray(String[]::new)); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + var sign = + new ArrayList( + List.of( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + validity, + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san)); + sign.addAll(startDate); + runKeytool(sign.toArray(String[]::new)); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java new file mode 100644 index 0000000000..b43910ce8f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java @@ -0,0 +1,437 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** + * Synthetic integrity fixtures only; these do not prove genuine owner rows, census, or authority. + */ +class SelectedOwnerIntakeSourceContentTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @Test + void roundTripsBothOwnerDomainsAndPreservesDefensiveExactFamilyBytes() { + DraftCommitBinding selected = binding(COMMIT); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner, selected, INTAKE); + List snapshots = snapshots(selected); + byte[] encoded = encode(scope, snapshots); + var content = SelectedOwnerIntakeSourceContent.fromStored(encoded, scope, digest(encoded)); + byte[] expected = snapshots.getFirst().bytes().clone(); + byte[] expectedContent = encoded.clone(); + byte[] exposedContent = content.canonicalBytes(); + byte[] exposedSnapshot = content.snapshotBytes("COMMAND"); + exposedContent[0] ^= 0x7f; + exposedSnapshot[0] ^= 0x7f; + encoded[0] ^= 0x7f; + + assertThat(content.scope()).isEqualTo(scope); + assertThat(content.canonicalBytes()).isEqualTo(expectedContent); + assertThat(content.canonicalBytes()).isNotEqualTo(exposedContent); + assertThat(content.digest()).isEqualTo(digest(encode(scope, snapshots))); + assertThat(content.snapshotBytes("COMMAND")).isEqualTo(expected); + assertThat(content.commandSource().binding()).isEqualTo(selected); + assertThat(content.commandSource().definitions()).isEmpty(); + assertThat(content.commandSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("COMMAND")); + assertThat(content.realmPolicySource().binding()).isEqualTo(selected); + assertThat(content.realmPolicySource().policies()).isEmpty(); + assertThat(content.realmPolicySource().canonicalBytes()) + .containsExactly(content.snapshotBytes("REALM_POLICY")); + assertThat(content.assetSource().binding()).isEqualTo(selected); + assertThat(content.assetSource().inheritedCommitId()).isNull(); + assertThat(content.assetSource().genesisReceiptId()).isEqualTo(GENESIS); + assertThat(content.assetSource().items()).isEmpty(); + assertThat(content.assetSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("ASSET")); + assertThat(content.brandingSource().binding()).isEqualTo(selected); + assertThat(content.brandingSource().inheritedCommitId()).isNull(); + assertThat(content.brandingSource().genesisReceiptId()).isEqualTo(GENESIS); + assertThat(content.brandingSource().items()).isEmpty(); + assertThat(content.brandingSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("BRANDING")); + assertThat(content.gameplaySource().binding()).isEqualTo(selected); + assertThat(content.templateConfigSource().binding()).isEqualTo(selected); + assertThatThrownBy(() -> content.snapshotBytes("UNKNOWN")) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void requiresExpectedScopeDigestAndEveryScopeFieldToMatch() { + DraftCommitBinding selected = binding(COMMIT); + var expectedScope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + byte[] original = encode(expectedScope, snapshots(selected)); + byte[] changedActor = + encode( + scope(Owner.ENTITY_MANAGEMENT, selected, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab")), + snapshots(selected)); + byte[] changedOwner = + encode(scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE), snapshots(selected)); + byte[] changedSelection = + encode( + scope( + Owner.ENTITY_MANAGEMENT, + binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")), + INTAKE), + snapshots(selected)); + + assertInvalid(original, expectedScope, "sha256:" + "0".repeat(64)); + assertInvalid(changedActor, expectedScope, digest(changedActor)); + assertInvalid(changedOwner, expectedScope, digest(changedOwner)); + assertInvalid(changedSelection, expectedScope, digest(changedSelection)); + assertInvalid( + encode(expectedScope, snapshots(selected), "sha256:" + "0".repeat(64), Map.of(), null), + expectedScope, + null); + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceContent.fromStored(original, expectedScope, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedSelectedBindingEvenWhenInnerAndOuterHashesAreRecomputed() { + DraftCommitBinding selected = binding(COMMIT); + DraftCommitBinding substituted = binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + List altered = snapshots(selected); + altered.set( + 0, + new FamilySnapshot( + "COMMAND", SelectedOwnerIntakeSourceTestFixtures.snapshot("COMMAND", substituted))); + byte[] forged = encode(scope, altered); + + assertInvalid(forged, scope, digest(forged)); + } + + @Test + void rejectsFamilyChangesAgainstThePreviouslyExpectedOuterDigest() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + byte[] original = encode(scope, snapshots(selected)); + List altered = snapshots(selected); + altered.set( + 0, + new FamilySnapshot( + "COMMAND", SelectedOwnerIntakeSourceTestFixtures.snapshot("COMMAND", selected, 1))); + byte[] changed = encode(scope, altered); + + assertInvalid(changed, scope, digest(original)); + } + + @Test + void rejectsWrongFamilyDigestAndNoncanonicalOrInvalidJsonContent() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List valid = snapshots(selected); + + assertInvalid( + encode(scope, valid, null, Map.of("COMMAND", "sha256:" + "0".repeat(64)), null), + scope, + null); + + List noncanonical = new ArrayList<>(valid); + noncanonical.set( + 0, + new FamilySnapshot( + "COMMAND", + (" " + new String(valid.getFirst().bytes(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, noncanonical), scope, null); + + List duplicate = new ArrayList<>(valid); + String bindingJson = selected.canonicalJson(); + String duplicateJson = + "{\"bindingJson\":" + + quote(bindingJson) + + ",\"bindingJson\":" + + quote(bindingJson) + + ",\"bindingDigest\":" + + quote(selected.digest()) + + "}"; + duplicate.set(0, new FamilySnapshot("COMMAND", duplicateJson.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, duplicate), scope, null); + + List emptyFamily = new ArrayList<>(valid); + emptyFamily.set(0, new FamilySnapshot("COMMAND", new byte[0])); + assertInvalid(encode(scope, emptyFamily), scope, null); + + List invalidUtf8 = new ArrayList<>(valid); + invalidUtf8.set(0, new FamilySnapshot("COMMAND", new byte[] {(byte) 0xc3, 0x28})); + assertInvalid(encode(scope, invalidUtf8), scope, null); + } + + @Test + void requiresTextualBindingFieldsAndTypedGameplayAndTemplateSnapshots() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List invalidBinding = new ArrayList<>(snapshots(selected)); + invalidBinding.set( + 0, + new FamilySnapshot( + "COMMAND", + GameplayRuleManifest.canonical( + Map.of("bindingJson", 1, "bindingDigest", selected.digest())) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, invalidBinding), scope, null); + + List missingBinding = new ArrayList<>(snapshots(selected)); + missingBinding.set( + 0, + new FamilySnapshot( + "COMMAND", + GameplayRuleManifest.canonical(Map.of("bindingJson", selected.canonicalJson())) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, missingBinding), scope, null); + + List invalidGameplay = new ArrayList<>(snapshots(selected)); + invalidGameplay.set( + 3, + new FamilySnapshot( + "GAMEPLAY_RULE", opaqueSnapshot("GAMEPLAY_RULE", selected, "typed-invalid"))); + assertInvalid(encode(scope, invalidGameplay), scope, null); + + List invalidTemplate = new ArrayList<>(snapshots(selected)); + invalidTemplate.set( + 5, + new FamilySnapshot( + "TEMPLATE_CONFIG", opaqueSnapshot("TEMPLATE_CONFIG", selected, "typed-invalid"))); + assertInvalid(encode(scope, invalidTemplate), scope, null); + } + + @Test + void rejectsMalformedTypedCommandPolicyAssetAndBrandingSnapshots() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + for (int index : List.of(0, 1, 2, 4)) { + List invalid = new ArrayList<>(snapshots(selected)); + FamilySnapshot original = invalid.get(index); + String field = index == 0 ? "definitions" : index == 1 ? "policies" : "items"; + String malformed = + new String(original.bytes(), StandardCharsets.UTF_8) + .replaceFirst("\"" + field + "\":\\[\\]", "\"" + field + "\":{}"); + invalid.set( + index, new FamilySnapshot(original.family(), malformed.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, invalid), scope, null); + } + } + + @Test + void rejectsChangedTypedSourceBindingWhenEnvelopeDigestsAreRecomputed() { + DraftCommitBinding selected = binding(COMMIT); + DraftCommitBinding substituted = binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + for (int index : List.of(0, 1, 2, 4)) { + List altered = new ArrayList<>(snapshots(selected)); + FamilySnapshot original = altered.get(index); + String changed = + new String(original.bytes(), StandardCharsets.UTF_8) + .replace(escaped(selected.canonicalJson()), escaped(substituted.canonicalJson())) + .replace(selected.digest(), substituted.digest()); + altered.set( + index, new FamilySnapshot(original.family(), changed.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, altered), scope, null); + } + } + + @Test + void rejectsOpaqueSelectedGameDesignRevisionWithOtherwiseTypedSnapshotEnvelope() { + DraftCommitBinding selected = binding(COMMIT, "{\"source\":1}"); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List typedSnapshots = snapshots(selected); + + assertInvalid(encode(scope, typedSnapshots), scope, null); + } + + @Test + void rejectsUnknownOrderDuplicateMissingTruncatedTrailingAndOversizedFrames() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + List valid = snapshots(selected); + + List swapped = new ArrayList<>(valid); + swapped.set(0, new FamilySnapshot("REALM_POLICY", valid.get(0).bytes())); + swapped.set(1, new FamilySnapshot("COMMAND", valid.get(1).bytes())); + assertInvalid(encode(scope, swapped), scope, null); + + List duplicate = new ArrayList<>(valid); + duplicate.set(1, new FamilySnapshot("COMMAND", valid.get(1).bytes())); + assertInvalid(encode(scope, duplicate), scope, null); + assertInvalid(encode(scope, valid.subList(0, 5)), scope, null); + + byte[] encoded = encode(scope, valid); + assertInvalid(encode(scope, valid, null, Map.of(), new byte[] {1}), scope, null); + assertInvalid(Arrays.copyOf(encoded, encoded.length - 1), scope, null); + + byte[] oversizedFrame = encoded.clone(); + ByteBuffer.wrap(oversizedFrame).putInt(0, Integer.MAX_VALUE); + assertInvalid(oversizedFrame, scope, null); + + byte[] oversizedEnvelope = new byte[SelectedOwnerIntakeSourceContent.MAX_BYTES + 1]; + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceContent.fromStored( + oversizedEnvelope, scope, "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static List snapshots(DraftCommitBinding selected) { + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var result = new ArrayList(); + for (String family : FAMILIES) { + byte[] bytes = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + }; + result.add(new FamilySnapshot(family, bytes)); + } + return result; + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static String escaped(String value) { + return value.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private static byte[] encode( + SelectedOwnerIntakeSourceReadScope scope, List snapshots) { + return encode(scope, snapshots, null, Map.of(), null); + } + + private static byte[] encode( + SelectedOwnerIntakeSourceReadScope scope, + List snapshots, + String scopeDigest, + Map familyDigests, + byte[] trailing) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scopeDigest == null ? scope.digest() : scopeDigest); + for (FamilySnapshot snapshot : snapshots) { + frame(out, snapshot.family()); + frame(out, snapshot.bytes()); + frame(out, familyDigests.getOrDefault(snapshot.family(), digest(snapshot.bytes()))); + } + if (trailing != null) out.writeBytes(trailing); + return out.toByteArray(); + } + + private static void assertInvalid( + byte[] bytes, SelectedOwnerIntakeSourceReadScope expectedScope, String expectedDigest) { + String digest = expectedDigest == null ? digest(bytes) : expectedDigest; + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceContent.fromStored(bytes, expectedScope, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected, UUID intakeRequestId) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, intakeRequestId, ACTOR, selected); + } + + private static DraftCommitBinding binding(UUID commitId) { + return binding(commitId, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + } + + private static DraftCommitBinding binding(UUID commitId, String revisionPayload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, revisionPayload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static String digest(byte[] value) { + return DraftAuthorizationFenceBinding.digest(value); + } + + private static String quote(String value) { + return GameplayRuleManifest.tree(GameplayRuleManifest.canonical(Map.of("value", value))) + .get("value") + .toString(); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record FamilySnapshot(String family, byte[] bytes) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java new file mode 100644 index 0000000000..1adbf6647b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.Test; + +/** Synthetic codec fixtures cover integrity mapping only, not genuine source-owner proof. */ +class SelectedOwnerIntakeSourceProtoCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @Test + void roundTripsBothOwnerRequestsAndCompleteSourceContent() { + DraftCommitBinding selected = + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = request(owner, selected); + var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + assertThat(SelectedOwnerIntakeSourceProtoCodec.fromRequest(wireRequest)).isEqualTo(request); + + var content = content(request.scope(), 0); + var wireResponse = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + assertThat(wireResponse.getRequest()).isEqualTo(wireRequest); + var decoded = SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, wireResponse); + assertThat(decoded.scope()).isEqualTo(request.scope()); + assertThat(decoded.digest()).isEqualTo(content.digest()); + assertThat(decoded.canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(decoded.snapshotBytes("COMMAND")).isEqualTo(content.snapshotBytes("COMMAND")); + } + } + + @Test + void rejectsChangedSchemaNamespaceCorrelationReaderPurposeScopeAndDigest() { + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); + var wire = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + + assertInvalidRequest(wire.toBuilder().setSchemaVersion(2).build()); + assertInvalidRequest(wire.toBuilder().setTargetNamespace("other").build()); + assertInvalidRequest(wire.toBuilder().setReadRequestId("not-a-uuid").build()); + assertInvalidRequest(wire.toBuilder().setIntendedReader("spiffe://wrong").build()); + assertInvalidRequest(wire.toBuilder().setPurpose("PUBLICATION").build()); + assertInvalidRequest(wire.toBuilder().clearPreliminarySourceScope().build()); + assertInvalidRequest( + wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build()); + } + + @Test + void requiresTheFullUnchangedRequestEchoBeforeInspectingContent() { + var request = + request( + Owner.AUTOMATION_SCRIPTING, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); + var content = content(request.scope(), 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + List> substitutions = + List.of( + builder -> builder.setSchemaVersion(2), + builder -> builder.setTargetNamespace("other"), + builder -> builder.setReadRequestId(UUID.randomUUID().toString()), + builder -> builder.setIntendedReader("spiffe://wrong"), + builder -> builder.setPurpose("PUBLICATION"), + builder -> builder.setPreliminarySourceScope(ByteString.copyFromUtf8("substituted")), + builder -> builder.setPreliminaryScopeDigest("sha256:" + "0".repeat(64))); + + for (var substitution : substitutions) { + var changedEcho = substitution.apply(response.getRequest().toBuilder()).build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setRequest(changedEcho).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownOuterAndNestedFields() { + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); + var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + var response = + SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content(request.scope(), 0)); + var unknown = unknownFields(); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsContentDigestAndScopeSubstitution() { + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); + var original = content(request.scope(), 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, original); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setSelectedSourceDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setSelectedSourceContent(ByteString.copyFromUtf8("changed")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearSelectedSourceContent().build())) + .isInstanceOf(IllegalArgumentException.class); + + var substitutedScope = scope(Owner.AUTOMATION_SCRIPTING, request.scope().selected()); + var substitutedContent = content(substitutedScope, 0); + var scopeSubstitution = + response.toBuilder() + .setSelectedSourceContent(ByteString.copyFrom(substitutedContent.canonicalBytes())) + .setSelectedSourceDigest(substitutedContent.digest()) + .build(); + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, scopeSubstitution)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void admitsContentAboveDefaultGrpcMessageSizeAndRejectsOversizedWireEnvelopes() { + var request = + request( + Owner.AUTOMATION_SCRIPTING, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); + var largeContent = content(request.scope(), 6_500_000); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, largeContent); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES); + assertThat(SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, response).digest()) + .isEqualTo(largeContent.digest()); + + var oversized = + SelectedOwnerIntakeSourceResponse.newBuilder() + .setRequest(SelectedOwnerIntakeSourceProtoCodec.toRequest(request)) + .setSelectedSourceContent( + ByteString.copyFrom(new byte[SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES])) + .setSelectedSourceDigest("sha256:" + "0".repeat(64)) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidRequest(SelectedOwnerIntakeSourceRequest wire) { + assertThatThrownBy(() -> SelectedOwnerIntakeSourceProtoCodec.fromRequest(wire)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, DraftCommitBinding selected) { + return SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope(owner, selected)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, NAMESPACE, OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, int largeCommandMarkerSize) { + var selected = scope.selected(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : FAMILIES) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> + SelectedOwnerIntakeSourceTestFixtures.snapshot( + family, selected, family.equals("COMMAND") ? largeCommandMarkerSize : 0); + }; + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] encoded = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); + } + + private static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST_ID, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java new file mode 100644 index 0000000000..63f6e6ff59 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; + +/** Synthetic canonical typed source snapshots for selected-owner Common tests. */ +public final class SelectedOwnerIntakeSourceTestFixtures { + private static final UUID GENESIS = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final String GENESIS_DIGEST = "sha256:" + "a".repeat(64); + + private SelectedOwnerIntakeSourceTestFixtures() {} + + public static byte[] snapshot(String family, DraftCommitBinding selected) { + return snapshot(family, selected, 0); + } + + /** Canonical delete of a synthetic command for otherwise inert selected-source bindings. */ + public static String selectedRevisionPayload() { + return CommandSource.deletePayload("synthetic-fixture-command"); + } + + /** Uses a valid, oversized command field when the transport test needs a large response body. */ + public static byte[] snapshot( + String family, DraftCommitBinding selected, int largeCommandFieldSize) { + return switch (family) { + case "COMMAND" -> command(selected, largeCommandFieldSize).canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, GENESIS, List.of()).canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> gameplay(selected).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static CommandSnapshot command(DraftCommitBinding selected, int largeCommandFieldSize) { + if (largeCommandFieldSize < 0) + throw new IllegalArgumentException("Command field size must be nonnegative"); + List definitions = + largeCommandFieldSize == 0 + ? List.of() + : List.of( + new CommandSource.Definition( + "synthetic-large-command", + CommandSource.canonical( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("commandId", "synthetic-large-command"), + Map.entry("semanticOwner", "x".repeat(largeCommandFieldSize)), + Map.entry("executionDiscipline", "DURABLE_GAMEPLAY"), + Map.entry("stageRequirement", "NONE"), + Map.entry("promptPolicy", "NEVER"), + Map.entry("actionCategory", "META"), + Map.entry("historyRecordable", false), + Map.entry("aliases", List.of()), + Map.entry("actionTags", List.of()), + Map.entry("effects", List.of()))), + selected.commitId(), + selected.revisions().getFirst().revisionId(), + selected.revisions().getFirst().revisionOrder())); + return new CommandSnapshot(selected, "0", null, GENESIS_DIGEST, definitions); + } + + private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 561b0e0de3..2487dd676f 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -66,6 +66,8 @@ val gameDesignClassesProof by configurations.creating { // Composed owner proofs load foreign migrations from disk; classes-only artifacts omit them. tasks.named("crossServiceTest") { + inputs.dir(rootProject.layout.projectDirectory.dir("services/account-service/src/main/resources/db/migration")) + .withPropertyName("accountOwnerMigrations") inputs.dir(rootProject.layout.projectDirectory.dir("services/game-logic-service/src/main/resources/db/migration")) .withPropertyName("gameLogicOwnerMigrations") inputs.dir(rootProject.layout.projectDirectory.dir("services/world-management-service/src/main/resources/db/migration")) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java new file mode 100644 index 0000000000..958612cfc6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact branding-source application evidence, composed into one control-plane owner result. */ +public record BrandingSourceApplication( + DraftCommitBinding binding, String expectedEpoch, BrandingSourceSnapshot snapshot) { + public BrandingSourceApplication { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || BrandingSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Branding asset application must advance its exact bound epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + BrandingSource.SCOPE, + binding.target().canonicalVersionId().toString(), + BrandingSource.SCOPE, + BrandingSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-branding-asset-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java new file mode 100644 index 0000000000..354e7ffbee --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java @@ -0,0 +1,543 @@ +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.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +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; + +/** + * Actual branding source writes under the existing coordinator; never total inventory authority. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local injected persistence collaborator") +public final class BrandingSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public BrandingSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public BrandingSourceSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var policyGenesis = + new RealmPolicySourceRepository(dsl) + .readGenesis(target) + .orElseThrow( + () -> new IllegalStateException("BRANDING_SOURCE_POLICY_GENESIS_UNAVAILABLE")); + var prior = readGenesis(target); + if (prior.isPresent()) { + var retained = prior.orElseThrow(); + if (!policyGenesis.creationTransactionId().equals(retained.creationTransactionId())) { + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_IDENTITY_CONFLICT"); + } + return retained; + } + 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("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); + String creationTransactionId = witness.get(0, String.class); + if (!policyGenesis.creationTransactionId().equals(creationTransactionId)) { + throw new IllegalStateException("BRANDING_SOURCE_CREATION_WITNESS_CONFLICT"); + } + var genesis = + new BrandingSourceSnapshot.Genesis( + target, UUID.randomUUID(), policyGenesis.creationTransactionId()); + dsl.execute( + "INSERT INTO game_design_branding_source_genesis " + + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json, roles_json) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + genesis.receiptId(), + genesis.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target)), + CommandSource.canonical(BrandingSource.emptyRoleDeclarations())); + dsl.execute( + "INSERT INTO game_design_branding_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + genesis.receiptId()); + if (!genesis.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_READBACK_CONFLICT"); + return genesis; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class) + || !CommandSource.canonical(BrandingSource.emptyRoleDeclarations()) + .equals(row.get("roles_json", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new BrandingSourceSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var mutations = BrandingSource.mutations(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!binding.requestId().equals(slot.requestId()) + || !binding.commitId().equals(slot.commitId()) + || owner == null + || (owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) + throw new IllegalStateException("BRANDING_SOURCE_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(BrandingSourceRepository::isScope) + .toList(); + String epoch = head.get("source_epoch", String.class); + if (units.size() != 1 + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("BRANDING_SOURCE_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + requirePreviousFence(binding.target(), inherited); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + if (inherited == null && !"0".equals(epoch)) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_NOT_CURRENT"); + // Lock all actual source rows in owner-key order before writing any revision history. + mutations.stream() + .filter(m -> m.operation() == BrandingSource.OperationKind.UPSERT) + .map(m -> Long.parseLong(m.assetRowId())) + .distinct() + .sorted() + .forEach( + id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("BRANDING_SOURCE_ROW_UNAVAILABLE"); + }); + for (var mutation : mutations) { + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item item = + mutation.operation() == BrandingSource.OperationKind.UPSERT + ? qualify( + new BrandingSource.Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.role(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()), + true) + : null; + dsl.execute( + "INSERT INTO game_design_branding_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, usage_key, role, asset_id, requiredness, content_type, content_digest, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + mutation.usageKey(), + mutation.role().name(), + item == null ? null : Long.parseLong(mutation.assetRowId()), + item == null ? null : mutation.requiredness().name(), + item == null ? null : item.contentType(), + item == null ? null : item.contentDigest(), + item == null ? null : item.byteSize()); + } + var references = + BrandingSource.replay( + previous.stream() + .map( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item + ::reference) + .toList(), + binding) + .references(); + var snapshot = + new BrandingSourceSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + references.stream().map(r -> qualify(r, false)).toList()); + var result = new BrandingSourceApplication(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_branding_source_application " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_branding_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 CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("BRANDING_SOURCE_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public BrandingSourceSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = readSnapshot(binding.target(), binding.commitId()); + if (prior.isPresent()) { + if (!prior.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + return prior.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + BrandingSourceSnapshot snapshot; + if (!BrandingSource.mutations(binding).isEmpty()) { + var result = + applied.orElseThrow( + () -> new IllegalStateException("BRANDING_SOURCE_APPLICATION_UNAVAILABLE")); + snapshot = result.snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("BRANDING_SOURCE_PREDECESSOR_CHANGED"); + } else { + var items = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + snapshot = + new BrandingSourceSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + items); + } + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_branding_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + dsl.execute( + "UPDATE game_design_branding_source_head 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 Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json, snapshot_digest FROM game_design_branding_source_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 = BrandingSourceSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_READBACK_CONFLICT"); + exact(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 request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) { + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyItems(snapshot); + return Optional.of(snapshot); + } + + public BrandingSourceSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("BRANDING_SOURCE_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("BRANDING_SOURCE_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("BRANDING_SOURCE_NOT_SYNCHRONIZED"); + var capture = new BrandingSourceSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_branding_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new BrandingSourceSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_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(); + var result = + new BrandingSourceApplication( + binding, + row.get("expected_epoch", String.class), + BrandingSourceSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class)) + || !binding.requestId().equals(row.get("request_id", UUID.class))) + throw new IllegalStateException("BRANDING_SOURCE_APPLICATION_READBACK_CONFLICT"); + verifyItems(result.snapshot()); + return Optional.of(result); + } + + private net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item qualify( + BrandingSource.Reference reference, boolean lock) { + var target = reference.sourceBinding().target(); + var row = + dsl.fetchOne( + "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?" + + (lock ? " FOR UPDATE" : ""), + target.gameDesignVersionTenantKey(), + Long.parseLong(reference.assetRowId())); + if (row == null + || !reference.usageKey().equals(row.get("file_name", String.class)) + || row.get("data", byte[].class) == null) + throw new IllegalStateException("BRANDING_SOURCE_EXACT_BYTES_UNAVAILABLE"); + byte[] bytes = row.get("data", byte[].class); + return new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( + reference, + row.get("content_type", String.class), + CommandSource.sha256(bytes), + bytes.length); + } + + private void verifyItems(BrandingSourceSnapshot snapshot) { + for (var item : snapshot.items()) { + if (!item.equals(qualify(item.reference(), false))) + throw new IllegalStateException("BRANDING_SOURCE_BYTE_READBACK_CONFLICT"); + var r = item.reference(); + var row = + dsl.fetchOne( + "SELECT content_digest, content_type, byte_size FROM game_design_branding_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND commit_id = ? AND request_id = ? AND revision_order = ? AND asset_id = ? AND usage_key = ? AND role = ? AND requiredness = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + r.revisionId(), + r.sourceBinding().commitId(), + r.sourceBinding().requestId(), + Integer.parseInt(r.revisionOrder()), + Long.parseLong(r.assetRowId()), + r.usageKey(), + r.role().name(), + r.requiredness().name()); + if (row == null + || !item.contentDigest().equals(row.get("content_digest", String.class)) + || !item.contentType().equals(row.get("content_type", String.class)) + || item.byteSize() != row.get("byte_size", Long.class)) + throw new IllegalStateException("BRANDING_SOURCE_REVISION_READBACK_CONFLICT"); + } + } + + private Record head(TargetProof target) { + return readHead(target, true); + } + + private Record readHead(TargetProof target, boolean lock) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("BRANDING_SOURCE_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (lock ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()), + "BRANDING_SOURCE_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("BRANDING_SOURCE_BINDING_CHANGED"); + } + + private void requirePreviousFence(TargetProof target, UUID inherited) { + var fence = coordinator.readVisibilityFence(target); + if (inherited == null + ? fence.isPresent() + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("BRANDING_SOURCE_PREVIOUS_FENCE_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("BRANDING_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null + || dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()) + != null) throw new IllegalStateException("BRANDING_SOURCE_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var qualified = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("BRANDING_SOURCE_TARGET_CHANGED"); + } + + static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return BrandingSource.SCOPE.equals(unit.aggregateType()) + && BrandingSource.SCOPE.equals(unit.scopeType()) + && BrandingSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Branding asset source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java new file mode 100644 index 0000000000..3d830052d3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.List; +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.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item; +import net.firedevops.firemud.common.gamedesign.CommandSource; + +/** Branding selected source only; no total inventory or template completeness claim. */ +public record BrandingSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public BrandingSourceSnapshot { + var value = + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + items = value.items(); + } + + @Override + public List items() { + return List.copyOf(items); + } + + public String canonicalJson() { + return shared().canonicalJson(); + } + + public byte[] canonicalBytes() { + return shared().canonicalBytes(); + } + + public String digest() { + return shared().digest(); + } + + public Map roleDeclarations() { + return shared().roleDeclarations(); + } + + public static BrandingSourceSnapshot fromStored(String json) { + return fromShared( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + } + + public static BrandingSourceSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot value) { + return new BrandingSourceSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.items()); + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + if (receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Exact branding source creation evidence required"); + } + + public Map roleDeclarations() { + return BrandingSource.emptyRoleDeclarations(); + } + } + + public record Capture(GameDesignPublicationOperation operation, BrandingSourceSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException("Branding asset capture differs from selected commit"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-branding-asset-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()); + } + } +} 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 index 65f7993ee8..4bf9e8c8f8 100644 --- 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 @@ -8,6 +8,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; /** Exact staged command-source application evidence, separate from the combined owner outcome. */ 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 index a4085e12d4..8c014f6c5c 100644 --- 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 @@ -1,11 +1,10 @@ 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; +import net.firedevops.firemud.common.gamedesign.CommandSource; /** Complete effective command set captured at one actual synchronized Draft commit. */ public record CommandSnapshot( @@ -15,16 +14,10 @@ public record CommandSnapshot( 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); + var value = + new net.firedevops.firemud.common.gamedesign.CommandSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptDigest, definitions); + definitions = value.definitions(); } @Override @@ -33,70 +26,34 @@ public List 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)))); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public String digest() { - return CommandSource.sha256(canonicalBytes()); + return shared().digest(); } 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; + return fromShared(net.firedevops.firemud.common.gamedesign.CommandSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.CommandSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.CommandSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptDigest, definitions); + } + + public static CommandSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.CommandSnapshot value) { + return new CommandSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptDigest(), + value.definitions()); } /** Frozen source paired with the actual operation bytes and selected synchronized snapshot. */ @@ -125,10 +82,4 @@ 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 deleted file mode 100644 index d04db8f1a1..0000000000 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ /dev/null @@ -1,653 +0,0 @@ -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.gamedesign.AssetSource; -import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; -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 and ordinary asset - * reference payloads are separate Game Design owner scopes and are left to their typed writers. - * 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) - || AssetSource.REVISION_KIND.equals(revisionKind) - || GameplayRuleSource.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) - && !AssetSource.REVISION_KIND.equals(revisionKind) - && !GameplayRuleSource.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) { - if (effective.remove(mutation.stableKey()) == null) { - throw new IllegalArgumentException("Cannot delete an absent command definition key"); - } - } 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 index baebc91ae0..26bd6ab1d4 100644 --- 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 @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; import org.jooq.DSLContext; @@ -127,9 +129,15 @@ public Optional apply(DraftCommitBinding binding) { List mutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean brandingMutation = !BrandingSource.mutations(binding).isEmpty(); boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireCompleteControlPlaneScopes( - binding, mutations, policyMutation, assetMutation, templateConfigMutation); + binding, + mutations, + policyMutation, + assetMutation, + brandingMutation, + templateConfigMutation); Optional existing = application(binding); if (existing.isPresent()) return existing; if (mutations.isEmpty()) return Optional.empty(); @@ -225,6 +233,7 @@ public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { mutations, CommandSource.hasRealmPolicyRevision(binding), !AssetSource.mutations(binding).isEmpty(), + !BrandingSource.mutations(binding).isEmpty(), !TemplateConfigSource.mutations(binding).isEmpty()); List definitions; if (!mutations.isEmpty()) { @@ -551,6 +560,7 @@ private void requireCompleteControlPlaneScopes( List commandMutations, boolean policyMutation, boolean assetMutation, + boolean brandingMutation, boolean templateConfigMutation) { List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); @@ -560,6 +570,8 @@ private void requireCompleteControlPlaneScopes( units.stream().filter(this::isPolicyScope).toList(); List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); + List branding = + units.stream().filter(BrandingSourceRepository::isScope).toList(); var gameplay = units.stream() .filter(net.firedevops.firemud.common.gamedesign.GameplayRuleSource::isScope) @@ -570,11 +582,13 @@ private void requireCompleteControlPlaneScopes( if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) || assets.size() != (assetMutation ? 1 : 0) + || branding.size() != (brandingMutation ? 1 : 0) || gameplay.size() != (gameplayMutation ? 1 : 0) || templateConfigs.size() != (templateConfigMutation ? 1 : 0) || commands.size() + policies.size() + assets.size() + + branding.size() + gameplay.size() + templateConfigs.size() != units.size()) { @@ -584,6 +598,7 @@ private void requireCompleteControlPlaneScopes( if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); + if (!branding.isEmpty()) requireScopeTarget(branding.getFirst(), binding.target()); if (!gameplay.isEmpty()) requireScopeTarget(gameplay.getFirst(), binding.target()); if (!templateConfigs.isEmpty()) requireScopeTarget(templateConfigs.getFirst(), binding.target()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java new file mode 100644 index 0000000000..7e91d460ab --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; + +/** Unregistered complete selected-content endpoint; never supplies an owner retention grant. */ +public final class GameDesignSelectedOwnerIntakeSourceGrpcService + extends GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceImplBase { + private final GameDesignSelectedOwnerIntakeSourceReadService owner; + private final String namespace; + + public GameDesignSelectedOwnerIntakeSourceGrpcService( + GameDesignSelectedOwnerIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readSelectedSource( + SelectedOwnerIntakeSourceRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() > SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request + decoded; + try { + decoded = SelectedOwnerIntakeSourceProtoCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var export = owner.readSource(decoded.scope()); + if (export == null) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + var content = + SelectedOwnerIntakeSourceContent.fromStored( + export.canonicalBytes(), decoded.scope(), export.digest()); + observer.onNext(SelectedOwnerIntakeSourceProtoCodec.toResponse(decoded, content)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + if (code == Status.Code.PERMISSION_DENIED || code == Status.Code.FAILED_PRECONDITION) { + observer.onError(Status.fromCode(code).asRuntimeException()); + } else { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java new file mode 100644 index 0000000000..4624f10a27 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered selected-owner source read that obtains exact Account permission before opening the + * independent Game Design source transaction. + */ +public final class GameDesignSelectedOwnerIntakeSourceReadService { + private final GameDesignSourceRepository repository; + private final SelectedOwnerIntakeSourceReadClient permissions; + private final String namespace; + private final TransactionTemplate transaction; + + public GameDesignSelectedOwnerIntakeSourceReadService( + GameDesignSourceRepository repository, + PlatformTransactionManager transactions, + SelectedOwnerIntakeSourceReadClient permissions, + String namespace) { + this.repository = Objects.requireNonNull(repository, "source repository is required"); + this.permissions = Objects.requireNonNull(permissions, "Account permission client is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public SelectedOwnerIntakeSourceExport readSource(SelectedOwnerIntakeSourceReadScope scope) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (scope == null || !namespace.equals(scope.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (!scope.intendedReader().equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Game Design owner read required") + .asRuntimeException(); + } + + var permissionRequest = SelectedOwnerIntakeSourceReadEvidence.Request.create(namespace, scope); + var permission = permissions.read(permissionRequest); + if (permission == null || !permissionRequest.equals(permission.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account source permission required") + .asRuntimeException(); + } + + return transaction.execute( + ignored -> { + var exported = repository.requireSelectedOwnerIntakeSource(scope); + if (exported == null + || !Arrays.equals(scope.canonicalBytes(), exported.scope().canonicalBytes()) + || !scope.digest().equals(exported.scope().digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source scope differs") + .asRuntimeException(); + } + byte[] canonicalBytes = exported.canonicalBytes(); + if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(exported.digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source export digest differs") + .asRuntimeException(); + } + return exported; + }); + } +} 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 5f7e4427b9..3e99a47944 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 @@ -7,12 +7,15 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; 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.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; @@ -26,7 +29,7 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Joins command, policy, and ordinary asset sources under one coordinator transaction. */ +/** Joins the authored source families under one caller-owned coordinator transaction. */ public final class GameDesignSourceRepository { private static final Comparator APPLIED_EPOCH_ORDER = Comparator.comparing(AppliedEpoch::aggregateType) @@ -38,6 +41,7 @@ public final class GameDesignSourceRepository { private final RealmPolicySourceRepository policies; private final CommandSourceRepository commands; private final AssetSourceRepository assets; + private final BrandingSourceRepository branding; private final GameplayRuleSourceRepository gameplay; private final TemplateConfigSourceRepository templateConfigs; private final DraftCommitCoordinatorRepository coordinator; @@ -47,6 +51,7 @@ public GameDesignSourceRepository(DSLContext dsl) { policies = new RealmPolicySourceRepository(dsl); commands = new CommandSourceRepository(dsl); assets = new AssetSourceRepository(dsl); + branding = new BrandingSourceRepository(dsl); gameplay = new GameplayRuleSourceRepository(dsl); templateConfigs = new TemplateConfigSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); @@ -72,6 +77,7 @@ public Genesis enrollFreshDraft(TargetProof target) { new CommandSource.NewDraftGenesisReceipt( target, policy.receiptId(), policy.creationTransactionId())); AssetSnapshot.Genesis asset = assets.enrollFreshDraft(target); + BrandingSourceSnapshot.Genesis brand = branding.enrollFreshDraft(target); var rules = gameplay.enrollFreshDraft(target); var templateConfig = templateConfigs.enrollFreshDraft(target); Genesis result = @@ -80,6 +86,7 @@ public Genesis enrollFreshDraft(TargetProof target) { command, Optional.of(asset), Optional.of(rules), + Optional.of(brand), Optional.of(templateConfig)); if (!result.equals( readGenesis(target) @@ -97,19 +104,21 @@ public Optional readGenesis(TargetProof target) { var policy = policies.readGenesis(target); var command = commands.readNewDraftGenesis(target); var asset = assets.readGenesis(target); + var brand = branding.readGenesis(target); var rules = gameplay.readGenesis(target); var templateConfig = templateConfigs.readGenesis(target); if (policy.isEmpty() && command.isEmpty() && asset.isEmpty() + && brand.isEmpty() && rules.isEmpty() && templateConfig.isEmpty()) return Optional.empty(); - if (policy.isEmpty() || command.isEmpty()) { + if (policy.isEmpty() || command.isEmpty() || brand.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } return Optional.of( new Genesis( - policy.orElseThrow(), command.orElseThrow(), asset, rules, templateConfig)); + policy.orElseThrow(), command.orElseThrow(), asset, rules, brand, templateConfig)); } /** Pure typed owner/scope validation; this does not read storage or grant write authority. */ @@ -118,12 +127,14 @@ public void validateInput(DraftCommitBinding binding) { var commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean brandingMutation = !BrandingSource.mutations(binding).isEmpty(); boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireCompleteScopes( binding, !commandMutations.isEmpty(), policyMutation, assetMutation, + brandingMutation, !GameplayRuleSource.mutations(binding).isEmpty(), templateConfigMutation); } @@ -135,6 +146,7 @@ public Application apply(DraftCommitBinding binding) { List commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean brandingMutation = !BrandingSource.mutations(binding).isEmpty(); boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireGenesis(binding.target()); requireReviewed(binding); @@ -146,6 +158,10 @@ public Application apply(DraftCommitBinding binding) { if (asset.isPresent() != assetMutation) { throw new IllegalStateException("GAME_DESIGN_ASSET_APPLICATION_INCOMPLETE"); } + Optional brand = branding.apply(binding); + if (brand.isPresent() != brandingMutation) { + throw new IllegalStateException("GAME_DESIGN_BRANDING_APPLICATION_INCOMPLETE"); + } var rules = gameplay.apply(binding); if (rules.isPresent() != !GameplayRuleSource.mutations(binding).isEmpty()) throw new IllegalStateException("GAMEPLAY_RULE_APPLICATION_INCOMPLETE"); @@ -159,12 +175,16 @@ public Application apply(DraftCommitBinding binding) { // first, then records the combined result using actual sibling readback bytes. policy = Optional.of( - command.isPresent() || asset.isPresent() || rules.isPresent() || templateConfig.isPresent() + command.isPresent() + || asset.isPresent() + || rules.isPresent() + || brand.isPresent() + || templateConfig.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); } OwnerOutcome expected; - if (asset.isPresent() || rules.isPresent() || templateConfig.isPresent()) { + if (asset.isPresent() || rules.isPresent() || brand.isPresent() || templateConfig.isPresent()) { ByteArrayOutputStream components = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame( components, "game-design-control-plane-sibling-components/v1"); @@ -184,6 +204,11 @@ public Application apply(DraftCommitBinding binding) { DraftAuthorizationFenceBinding.frame(components, rules.orElseThrow().canonicalBytes()); epochs.add(rules.orElseThrow().appliedEpoch()); } + if (brand.isPresent()) { + DraftAuthorizationFenceBinding.frame(components, "BRANDING"); + DraftAuthorizationFenceBinding.frame(components, brand.orElseThrow().canonicalBytes()); + epochs.add(brand.orElseThrow().appliedEpoch()); + } if (templateConfig.isPresent()) { DraftAuthorizationFenceBinding.frame(components, "TEMPLATE_CONFIG"); DraftAuthorizationFenceBinding.frame( @@ -243,7 +268,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, asset, rules, templateConfig, retained); + return new Application(binding, command, policy, asset, rules, brand, templateConfig, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -255,9 +280,11 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { CommandSnapshot command = commands.captureSynchronized(binding); RealmPolicySnapshot policy = policies.captureSynchronized(binding); AssetSnapshot asset = assets.captureSynchronized(binding); + BrandingSourceSnapshot brand = branding.captureSynchronized(binding); if (!binding.equals(command.binding()) || !binding.equals(policy.binding()) - || !binding.equals(asset.binding())) { + || !binding.equals(asset.binding()) + || !binding.equals(brand.binding())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); } var rules = @@ -268,7 +295,8 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { templateConfigs.readGenesis(binding.target()).isPresent() ? Optional.of(templateConfigs.captureSynchronized(binding)) : Optional.empty(); - return new SynchronizedSources(command, policy, Optional.of(asset), rules, templateConfig); + return new SynchronizedSources( + command, policy, Optional.of(asset), rules, Optional.of(brand), templateConfig); } /** Freeze complete selected source snapshots against the same current retained operation. */ @@ -288,11 +316,13 @@ public Capture freeze(GameDesignPublicationOperation operation) { } CommandSnapshot.Capture command = commands.freeze(operation); AssetSnapshot.Capture asset = assets.freeze(operation); + BrandingSourceSnapshot.Capture brand = branding.freeze(operation); var templateConfig = templateConfigs.readGenesis(operation.account().input().selection().target()).isPresent() ? Optional.of(templateConfigs.freeze(operation)) : Optional.empty(); - Capture result = new Capture(command, policy, Optional.of(asset), templateConfig); + Capture result = + new Capture(command, policy, Optional.of(asset), Optional.of(brand), templateConfig); Capture retained = readCapture(operation) .orElseThrow( @@ -303,6 +333,8 @@ public Capture freeze(GameDesignPublicationOperation operation) { || !Arrays.equals( result.asset().orElseThrow().canonicalBytes(), retained.asset().orElseThrow().canonicalBytes()) + || !optionalBrandingCaptureBytesEqual(result.branding(), retained.branding()) + || retained.branding().isEmpty() || !optionalCaptureBytesEqual(result.templateConfig(), retained.templateConfig())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); } @@ -317,10 +349,16 @@ public Optional readCapture(GameDesignPublicationOperation operation) { var command = commands.readCapture(operation); var policy = policies.readCapture(operation); var asset = assets.readCapture(operation); + var brand = branding.readCapture(operation); var target = operation.account().input().selection().target(); + boolean brandingSourceEnrolled = branding.readGenesis(target).isPresent(); boolean templateSourceEnrolled = templateConfigs.readGenesis(target).isPresent(); var templateConfig = templateConfigs.readCapture(operation); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && templateConfig.isEmpty()) + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && brand.isEmpty() + && templateConfig.isEmpty()) return Optional.empty(); if (historical) { new GameDesignReviewedBaseRepository(dsl) @@ -329,11 +367,12 @@ public Optional readCapture(GameDesignPublicationOperation operation) { if (command.isEmpty() || policy.isEmpty() || (asset.isEmpty() && !historical) + || (brand.isEmpty() && (!historical || brandingSourceEnrolled)) || (templateSourceEnrolled && templateConfig.isEmpty())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } return Optional.of( - new Capture(command.orElseThrow(), policy.orElseThrow(), asset, templateConfig)); + new Capture(command.orElseThrow(), policy.orElseThrow(), asset, brand, templateConfig)); } public Optional readSynchronized(TargetProof target, UUID commitId) { @@ -342,7 +381,15 @@ public Optional readSynchronized(TargetProof target, UUID c var command = commands.readSnapshot(target, commitId); var policy = policies.readSnapshot(target, commitId); var asset = assets.readSnapshot(target, commitId); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); + var brand = branding.readSnapshot(target, commitId); + var rules = gameplay.readSnapshot(target, commitId); + var templateConfig = templateConfigs.readSnapshot(target, commitId); + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && brand.isEmpty() + && rules.isEmpty() + && templateConfig.isEmpty()) return Optional.empty(); if (command.isEmpty() || policy.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } @@ -351,23 +398,45 @@ public Optional readSynchronized(TargetProof target, UUID c if (asset.isEmpty() && (assetGenesisRetained || !AssetSource.mutations(binding).isEmpty())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } - var rules = gameplay.readSnapshot(target, commitId); + boolean brandGenesisRetained = branding.readGenesis(target).isPresent(); + if (brand.isEmpty() + && (brandGenesisRetained || !BrandingSource.mutations(binding).isEmpty())) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); + } if (rules.isEmpty() && (gameplay.readGenesis(target).isPresent() || !GameplayRuleSource.mutations(binding).isEmpty())) throw new IllegalStateException("GAMEPLAY_RULE_SYNCHRONIZED_SOURCE_INCOMPLETE"); - var templateConfig = templateConfigs.readSnapshot(target, commitId); if (templateConfig.isEmpty() && (templateConfigs.readGenesis(target).isPresent() || !TemplateConfigSource.mutations(binding).isEmpty())) throw new IllegalStateException("TEMPLATE_CONFIG_SYNCHRONIZED_SOURCE_INCOMPLETE"); return Optional.of( new SynchronizedSources( - command.orElseThrow(), policy.orElseThrow(), asset, rules, templateConfig)); + command.orElseThrow(), policy.orElseThrow(), asset, rules, brand, templateConfig)); + } + + /** + * Read and export the exact synchronized source retained for an original selected Draft. + * Missing or partial owner history remains unavailable; it is never interpreted as empty. + */ + public SelectedOwnerIntakeSourceExport requireSelectedOwnerIntakeSource( + SelectedOwnerIntakeSourceReadScope scope) { + Objects.requireNonNull(scope, "scope"); + DraftCommitBinding selected = scope.selected(); + SynchronizedSources sources = + readSynchronized(selected.target(), selected.commitId()) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SELECTED_SOURCE_UNAVAILABLE")); + return SelectedOwnerIntakeSourceExport.create(scope, sources); } private void requireGenesis(TargetProof target) { - if (readGenesis(target).filter(genesis -> genesis.assetEvidence().isPresent()).isEmpty()) { + if (readGenesis(target) + .filter( + genesis -> + genesis.assetEvidence().isPresent() && genesis.brandingEvidence().isPresent()) + .isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); } } @@ -408,9 +477,15 @@ private static void requireCompleteScopes( boolean hasCommand, boolean hasPolicy, boolean hasAsset, + boolean hasBranding, boolean hasGameplay, boolean hasTemplateConfig) { - if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay && !hasTemplateConfig + if (!hasCommand + && !hasPolicy + && !hasAsset + && !hasBranding + && !hasGameplay + && !hasTemplateConfig || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -432,16 +507,20 @@ private static void requireCompleteScopes( && "effective".equals(unit.scopeId())) .toList(); List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); + List branding = + units.stream().filter(BrandingSourceRepository::isScope).toList(); var rules = units.stream().filter(GameplayRuleSource::isScope).toList(); var templateConfigs = units.stream().filter(TemplateConfigSource::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) || assets.size() != (hasAsset ? 1 : 0) + || branding.size() != (hasBranding ? 1 : 0) || rules.size() != (hasGameplay ? 1 : 0) || templateConfigs.size() != (hasTemplateConfig ? 1 : 0) || commands.size() + policies.size() + assets.size() + + branding.size() + rules.size() + templateConfigs.size() != units.size() @@ -474,11 +553,13 @@ public record Genesis( CommandSource.NewDraftGenesisReceipt command, Optional assetEvidence, Optional gameplayEvidence, + Optional brandingEvidence, Optional templateConfig) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); + brandingEvidence = Objects.requireNonNull(brandingEvidence, "brandingEvidence"); gameplayEvidence = Objects.requireNonNull(gameplayEvidence, "gameplayEvidence"); templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (gameplayEvidence.isPresent() @@ -490,6 +571,11 @@ public record Genesis( if (!policy.target().equals(command.target()) || !policy.receiptId().equals(command.receiptId()) || !policy.creationTransactionId().equals(command.creationTransactionId()) + || brandingEvidence.isPresent() + && (!policy.target().equals(brandingEvidence.orElseThrow().target()) + || !policy + .creationTransactionId() + .equals(brandingEvidence.orElseThrow().creationTransactionId())) || assetEvidence.isPresent() && (!policy.target().equals(assetEvidence.orElseThrow().target()) || !policy @@ -506,23 +592,44 @@ public record Genesis( } } + public Genesis( + RealmPolicyGenesis policy, + CommandSource.NewDraftGenesisReceipt command, + Optional assetEvidence, + Optional gameplayEvidence, + Optional templateConfig) { + this( + policy, + command, + assetEvidence, + gameplayEvidence, + Optional.empty(), + templateConfig); + } + public Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, Optional assetEvidence, Optional gameplayEvidence) { - this(policy, command, assetEvidence, gameplayEvidence, Optional.empty()); + this(policy, command, assetEvidence, gameplayEvidence, Optional.empty(), Optional.empty()); } public Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, Optional assetEvidence) { - this(policy, command, assetEvidence, Optional.empty(), Optional.empty()); + this(policy, command, assetEvidence, Optional.empty(), Optional.empty(), Optional.empty()); } public Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { - this(policy, command, Optional.empty(), Optional.empty(), Optional.empty()); + this( + policy, + command, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); } public AssetSnapshot.Genesis asset() { @@ -537,6 +644,7 @@ public record Application( Optional policy, Optional asset, Optional gameplay, + Optional branding, Optional templateConfig, OwnerOutcome ownerOutcome) { public Application { @@ -545,17 +653,20 @@ public record Application( policy = Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); gameplay = Objects.requireNonNull(gameplay, "gameplay"); + branding = Objects.requireNonNull(branding, "branding"); templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty() + && branding.isEmpty() && templateConfig.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || gameplay.isPresent() && !binding.equals(gameplay.orElseThrow().binding()) + || branding.isPresent() && !binding.equals(branding.orElseThrow().binding()) || templateConfig.isPresent() && !binding.equals(templateConfig.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE @@ -572,8 +683,17 @@ public Application( Optional policy, Optional asset, Optional gameplay, + Optional templateConfig, OwnerOutcome ownerOutcome) { - this(binding, command, policy, asset, gameplay, Optional.empty(), ownerOutcome); + this( + binding, + command, + policy, + asset, + gameplay, + Optional.empty(), + templateConfig, + ownerOutcome); } public Application( @@ -581,8 +701,34 @@ public Application( Optional command, Optional policy, Optional asset, + Optional gameplay, OwnerOutcome ownerOutcome) { - this(binding, command, policy, asset, Optional.empty(), Optional.empty(), ownerOutcome); + this( + binding, + command, + policy, + asset, + gameplay, + Optional.empty(), + Optional.empty(), + ownerOutcome); + } + + public Application( + DraftCommitBinding binding, + Optional command, + Optional policy, + Optional asset, + OwnerOutcome ownerOutcome) { + this( + binding, + command, + policy, + asset, + Optional.empty(), + Optional.empty(), + Optional.empty(), + ownerOutcome); } } @@ -591,12 +737,14 @@ public record SynchronizedSources( RealmPolicySnapshot policy, Optional assetEvidence, Optional gameplayEvidence, + Optional branding, Optional templateConfig) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); gameplayEvidence = Objects.requireNonNull(gameplayEvidence, "gameplayEvidence"); + branding = Objects.requireNonNull(branding, "branding"); templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (gameplayEvidence.isPresent() && !command.binding().equals(gameplayEvidence.orElseThrow().binding())) @@ -604,6 +752,9 @@ public record SynchronizedSources( if (templateConfig.isPresent() && !command.binding().equals(templateConfig.orElseThrow().binding())) throw new IllegalStateException("TEMPLATE_CONFIG_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + if (branding.isPresent() + && !command.binding().equals(branding.orElseThrow().binding())) + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_BINDING_CONFLICT"); if (!command.binding().equals(policy.binding()) || assetEvidence.isPresent() && !command.binding().equals(assetEvidence.orElseThrow().binding())) { @@ -615,7 +766,13 @@ public SynchronizedSources( CommandSnapshot command, RealmPolicySnapshot policy, Optional assetEvidence) { - this(command, policy, assetEvidence, Optional.empty(), Optional.empty()); + this( + command, + policy, + assetEvidence, + Optional.empty(), + Optional.empty(), + Optional.empty()); } public SynchronizedSources( @@ -623,7 +780,28 @@ public SynchronizedSources( RealmPolicySnapshot policy, Optional assetEvidence, Optional gameplayEvidence) { - this(command, policy, assetEvidence, gameplayEvidence, Optional.empty()); + this( + command, + policy, + assetEvidence, + gameplayEvidence, + Optional.empty(), + Optional.empty()); + } + + public SynchronizedSources( + CommandSnapshot command, + RealmPolicySnapshot policy, + Optional assetEvidence, + Optional gameplayEvidence, + Optional templateConfig) { + this( + command, + policy, + assetEvidence, + gameplayEvidence, + Optional.empty(), + templateConfig); } public AssetSnapshot asset() { @@ -636,11 +814,13 @@ public record Capture( CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy, Optional asset, + Optional branding, Optional templateConfig) { public Capture { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); + branding = Objects.requireNonNull(branding, "branding"); templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) || !command.snapshot().binding().equals(policy.snapshot().binding()) @@ -664,13 +844,31 @@ public record Capture( .equals(templateConfig.orElseThrow().snapshot().binding()))) { throw new IllegalStateException("GAME_DESIGN_TEMPLATE_CONFIG_CAPTURE_BINDING_CONFLICT"); } + if (branding.isPresent() + && (!Arrays.equals( + command.operation().canonicalBytes(), + branding.orElseThrow().operation().canonicalBytes()) + || !command + .snapshot() + .binding() + .equals(branding.orElseThrow().snapshot().binding()))) { + throw new IllegalStateException("GAME_DESIGN_BRANDING_CAPTURE_BINDING_CONFLICT"); + } } public Capture( CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy, Optional asset) { - this(command, policy, asset, Optional.empty()); + this(command, policy, asset, Optional.empty(), Optional.empty()); + } + + public Capture( + CommandSnapshot.Capture command, + RealmPolicySnapshot.Capture policy, + Optional asset, + Optional templateConfig) { + this(command, policy, asset, Optional.empty(), templateConfig); } } @@ -680,4 +878,11 @@ private static boolean optionalCaptureBytesEqual( if (left.isEmpty() || right.isEmpty()) return left.isEmpty() && right.isEmpty(); return Arrays.equals(left.orElseThrow().canonicalBytes(), right.orElseThrow().canonicalBytes()); } + + private static boolean optionalBrandingCaptureBytesEqual( + Optional left, + Optional right) { + if (left.isEmpty() || right.isEmpty()) return left.isEmpty() && right.isEmpty(); + return Arrays.equals(left.orElseThrow().canonicalBytes(), right.orElseThrow().canonicalBytes()); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java new file mode 100644 index 0000000000..0ff938d33e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** + * Complete selected six-family Game Design source content for a distinct owner intake read. + * + *

This value proves only that the supplied immutable snapshots are complete and bound to the + * exact selected Draft scope. Constructing it does not authenticate a caller, establish an Account + * reservation or finalization, or prove owner emptiness, owner receipt, or retention authority. + */ +public final class SelectedOwnerIntakeSourceExport { + public static final String DOMAIN = "game-design-selected-owner-intake-source/v1"; + public static final int MAX_BYTES = 8 * 1024 * 1024; + + private final SelectedOwnerIntakeSourceReadScope scope; + private final GameDesignSourceRepository.SynchronizedSources sources; + private final byte[] canonicalBytes; + private final String digest; + + private SelectedOwnerIntakeSourceExport( + SelectedOwnerIntakeSourceReadScope scope, + GameDesignSourceRepository.SynchronizedSources sources, + byte[] canonicalBytes) { + this.scope = scope; + this.sources = sources; + this.canonicalBytes = canonicalBytes.clone(); + this.digest = DraftAuthorizationFenceBinding.digest(this.canonicalBytes); + } + + public static SelectedOwnerIntakeSourceExport create( + SelectedOwnerIntakeSourceReadScope scope, + GameDesignSourceRepository.SynchronizedSources sources) { + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(sources, "sources"); + + DraftCommitBinding selected = scope.selected(); + requireSelected(selected, sources.command().binding(), "COMMAND"); + requireSelected(selected, sources.policy().binding(), "REALM_POLICY"); + requireSelected(selected, sources.asset().binding(), "ASSET"); + var gameplay = sources.gameplayEvidence().orElseThrow( + () -> new IllegalStateException("Selected gameplay-rule source is incomplete")); + requireSelected(selected, gameplay.binding(), "GAMEPLAY_RULE"); + var branding = + sources + .branding() + .orElseThrow(() -> new IllegalStateException("Selected branding source is incomplete")); + var templateConfig = + sources + .templateConfig() + .orElseThrow( + () -> new IllegalStateException("Selected template-config source is incomplete")); + requireSelected(selected, branding.binding(), "BRANDING"); + requireSelected(selected, templateConfig.binding(), "TEMPLATE_CONFIG"); + + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + addFamily(out, "COMMAND", sources.command().canonicalBytes()); + addFamily(out, "REALM_POLICY", sources.policy().canonicalBytes()); + addFamily(out, "ASSET", sources.asset().canonicalBytes()); + addFamily(out, "GAMEPLAY_RULE", gameplay.canonicalBytes()); + addFamily(out, "BRANDING", branding.canonicalBytes()); + addFamily(out, "TEMPLATE_CONFIG", templateConfig.canonicalBytes()); + return new SelectedOwnerIntakeSourceExport(scope, sources, out.toByteArray()); + } + + public SelectedOwnerIntakeSourceReadScope scope() { + return scope; + } + + /** The immutable family snapshot values used to construct this export. */ + public GameDesignSourceRepository.SynchronizedSources sources() { + return sources; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static void addFamily(ByteArrayOutputStream out, String family, byte[] bytes) { + frame(out, family); + frame(out, bytes); + frame(out, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static void frame(ByteArrayOutputStream out, byte[] bytes) { + DraftAuthorizationFenceBinding.frame(out, bytes); + requireWithinLimit(out); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + requireWithinLimit(out); + } + + private static void requireWithinLimit(ByteArrayOutputStream out) { + if (out.size() > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake source exceeds 8 MiB"); + } + } + + private static void requireSelected( + DraftCommitBinding selected, DraftCommitBinding family, String familyName) { + if (!selected.equals(family)) { + throw new IllegalStateException( + "Selected " + familyName + " source differs from the original Draft binding"); + } + } +} 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 f1bc1c0733..62de9f39ed 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 @@ -11,7 +11,7 @@ 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java new file mode 100644 index 0000000000..a7855c56a8 --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -0,0 +1,238 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Clock; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.account.sourceintake.GrpcSelectedOwnerIntakeSourceReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +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.Owner; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; +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.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +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; +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.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Account V1006 preliminary permission and independent GD six-family disclosure owners. + * Creator, environment, PKI, selected author admission/readbacks and authored inputs are controlled; + * no final intake authorization, recipient retention, genuine provenance or registration is proved. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class SelectedOwnerSourceDisclosurePostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + @Container static final PostgreSQLContainer GDS = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container static final PostgreSQLContainer ACCOUNT = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK).withNetworkAliases("selected-disclosure-primary") + .withExposedPorts(6379) + .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always"); + @Container static final GenericContainer REPLICA = new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK).dependsOn(REDIS) + .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always", "--replicaof", "selected-disclosure-primary", "6379"); + @TempDir Path temporary; + + @Test + void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefuses() throws Exception { + var local = sourceStore(); + try (var fixture = new AccountControlUiOriginalOrderFixture( + ACCOUNT.getJdbcUrl(), ACCOUNT.getUsername(), ACCOUNT.getPassword(), REDIS.getHost(), + REDIS.getMappedPort(6379), temporary.resolve("account"), local.binding().target().canonicalTenantId(), + Clock.systemUTC(), "1006")) { + var issued = fixture.preparedOriginalCreator(); + var f = issued.sources(); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version IN ('1007','1008','1009')").get(0, Integer.class)).isZero(); + retainControlledSelectedAuthorAdmission(issued, local.binding()); + var reservations = new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), f.manager, NAMESPACE); + var pki = new GenuineWorldSourceProofPki(temporary.resolve("pki")); + var endpoints = new ServiceEndpointsProperties(); + Server accountServer = null; + Server sourceServer = null; + try { + accountServer = server(pki, "account-service", new AccountSelectedOwnerIntakeSourceReadGrpcService( + fixture.selectedOwnerIntakeSourceReadService(NAMESPACE), NAMESPACE)); + endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); + try (var permissions = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, + pki.client("game-design-service"), new GrpcChannelFactory(), NAMESPACE)) { + permissions.init(); + var permissionCalls = new AtomicInteger(); + var sourceOwner = new GameDesignSelectedOwnerIntakeSourceReadService( + new GameDesignSourceRepository(local.dsl()), local.manager(), request -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + permissionCalls.incrementAndGet(); + return permissions.read(request); + }, NAMESPACE); + sourceServer = server(pki, "game-design-service", new GameDesignSelectedOwnerIntakeSourceGrpcService(sourceOwner, NAMESPACE)); + endpoints.setGameDesignService("127.0.0.1:" + sourceServer.getPort()); + try (var sources = new GrpcSelectedOwnerIntakeSourceClient(endpoints, + pki.client("account-service"), new GrpcChannelFactory(), NAMESPACE); + var wrongCaller = new GrpcSelectedOwnerIntakeSourceClient(endpoints, + pki.client("game-design-service"), new GrpcChannelFactory(), NAMESPACE)) { + sources.init(); + wrongCaller.init(); + for (var owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + UUID requestId = UUID.randomUUID(); + var scope = asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment())); + var retained = retainedReservation(f, scope); + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); + var content = sources.read(request); + var expected = local.tx().execute(ignored -> new GameDesignSourceRepository(local.dsl()).requireSelectedOwnerIntakeSource(scope)); + assertThat(content.canonicalBytes()).isEqualTo(expected.canonicalBytes()); + assertThat(content.digest()).isEqualTo(expected.digest()); + for (String family : List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) + assertThat(content.snapshotBytes(family)).isNotEmpty(); + assertThat(sources.read(SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope)).canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment())).canonicalBytes()).isEqualTo(scope.canonicalBytes()); + assertThat(retainedReservation(f, scope)).isEqualTo(retained); + int beforeWrongPeer = permissionCalls.get(); + assertThatThrownBy(() -> wrongCaller.read(request)).isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat(permissionCalls).hasValue(beforeWrongPeer); + var substituted = new SelectedOwnerIntakeSourceReadScope(owner, NAMESPACE, UUID.randomUUID(), scope.fenceId(), scope.intakeRequestId(), scope.actorAccountId(), scope.selected()); + assertThatThrownBy(() -> sources.read(SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, substituted))).isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat(retainedReservation(f, scope)).isEqualTo(retained); + assertThat(asGameDesign(() -> reservations.abortSourceRead(scope)).state().name()).isEqualTo("ABORTED"); + var aborted = retainedReservation(f, scope); + assertThatThrownBy(() -> sources.read(request)).isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment()))).isInstanceOf(io.grpc.StatusRuntimeException.class); + asGameDesign(() -> reservations.abortSourceRead(scope)); + assertThat(retainedReservation(f, scope)).isEqualTo(aborted); + assertThat(local.tx().execute(ignored -> new GameDesignSourceRepository(local.dsl()).requireSelectedOwnerIntakeSource(scope)).canonicalBytes()).isEqualTo(content.canonicalBytes()); + } + } + } + } finally { + for (var server : new Server[] {sourceServer, accountServer}) if (server != null) server.shutdownNow(); + for (var server : new Server[] {sourceServer, accountServer}) if (server != null) assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static String retainedReservation(AccountControlUiOwnerSourcesFixture f, SelectedOwnerIntakeSourceReadScope scope) { + return f.dsl.fetchSingle("SELECT row_to_json(r)::TEXT || ':' || xmin::TEXT FROM account_selected_owner_intake_source_read_reservations r WHERE operation_id = ?", scope.operationId()).get(0, String.class); + } + + /** Controlled upstream terminal readbacks; the preliminary permission itself is never mocked. */ + private static void retainControlledSelectedAuthorAdmission(AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { + var f = issued.sources(); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = new DraftAuthorizationFenceBinding(UUID.randomUUID(), selected.requestId(), selected.commitId(), UUID.randomUUID(), f.account.getAccountUuid(), f.tenant, selected.target().canonicalVersionId(), selected.baseCommitId(), "0", selected.canonicalBytes(), selected.canonicalBytes(), selected.digest(), captured.sources()).withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + f.tx(() -> { + for (var owner : original.requiredOwners()) f.fences.recordOwnerReadback(original, + new DraftAuthorizationFenceBinding.OwnerReadback(owner, DraftAuthorizationFenceBinding.Outcome.COMMITTED, original.operationId(), original.commitId(), original.fenceId(), original.inputDigest(), original.canonicalBytes(), new byte[] {1})); + return null; + }); + } + + private static Local sourceStore() { + String schema = "selected_disclosure_" + UUID.randomUUID().toString().replace("-", ""); + var data = new DriverManagerDataSource(GDS.getJdbcUrl(), GDS.getUsername(), GDS.getPassword()); + data.setSchema(schema); + Flyway.configure().dataSource(data).schemas(schema).defaultSchema(schema) + .table("flyway_schema_history_game_design_service").placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration").load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(data); + var tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Controlled selected source disclosure"); + var savedGame = tx.execute(ignored -> new GameRepository(dsl).save(game)); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = tx.execute(ignored -> new VersionRepository(dsl).save(version)); + var target = new DraftCommitBinding.TargetProof(saved.getCanonicalTenantId(), saved.getCanonicalVersionId(), saved.getId(), saved.getTenantId(), saved.getIdentitySourceGameRowId(), saved.getIdentitySourceGameTenantKey(), saved.getIdentitySourceProvenanceKind()); + var binding = DraftCommitBinding.create(target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", + List.of(new DraftCommitBinding.RevisionPayload("0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload("{\"schemaVersion\":1,\"commandId\":\"DISCLOSURE\",\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true,\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"))), + List.of(new DraftCommitBinding.AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE, CommandSource.SCOPE, target.canonicalVersionId().toString(), CommandSource.SCOPE, "effective", "0"))); + tx.executeWithoutResult(ignored -> { + var source = new GameDesignSourceRepository(dsl); + var reviewed = new GameDesignReviewedBaseRepository(dsl).resolve(target, DraftBaseReference.parse(binding.baseCommitId())); + source.claimReviewed(binding, reviewed); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = source.apply(binding); + coordinator.advanceSourceVisibilityFence(binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(applied.ownerOutcome()))); + source.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + return new Local(dsl, manager, tx, binding); + } + + private static Server server(GenuineWorldSourceProofPki pki, String service, io.grpc.BindableService handler) throws Exception { + var identity = pki.server(service); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()).trustManager(pki.ca().toFile()).clientAuth(ClientAuth.REQUIRE).build()) + .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())).build().start(); + } + + private static T asGameDesign(Supplier action) { + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service").orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private record Local(DSLContext dsl, DataSourceTransactionManager manager, TransactionTemplate tx, DraftCommitBinding binding) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..25674b7d74 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -0,0 +1,468 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.gamedesign.entity.Game; +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.publication.BrandingSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +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; +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; + +/** Physical storage proof only; Account creator admission is not simulated by this fixture. */ +@Testcontainers(disabledWithoutDocker = true) +class BrandingSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalHistory() + throws Exception { + var f = fixture(null); + var logo = asset(f, "logo.png"); + var ordinary = asset(f, "ordinary.png"); + // Borrow only typed policy input; the fixture is not Account publication authorization. + var policy = + net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures.fresh( + f.target) + .account() + .input() + .selection() + .selectedCommit() + .revisions() + .stream() + .map(DraftCommitBinding.RevisionPayload::payload) + .filter(p -> p.contains("REALM_ENTRY_POLICY")) + .findFirst() + .orElseThrow(); + var first = + binding( + f, + "0", + BrandingSource.SCOPE, + BrandingSource.upsertPayload( + logo.getId().toString(), + "logo.png", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED), + AssetSource.upsertPayload( + ordinary.getId().toString(), "ordinary.png", AssetSource.Requiredness.REQUIRED), + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("branding-proof")), + commandUpsert("BRANDING_INITIAL"), + policy); + apply(f, first); + var synchronizedSources = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, first.commitId()) + .orElseThrow(); + var selected = synchronizedSources.branding().orElseThrow(); + assertThat(selected.items()).hasSize(1); + assertThat(selected.items().getFirst().reference().sourceBinding()).isEqualTo(first); + assertThat(selected.roleDeclarations()) + .containsEntry("LOGO", "PRESENT") + .containsEntry("THEME", "EMPTY"); + assertThat( + synchronizedSources + .gameplay() + .manifest() + .families() + .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + .containsExactly(new GameplayRuleManifest.AdmissionTag("branding-proof")); + assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, UUID.randomUUID())) + .isEmpty(); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_assets SET data = ? WHERE id = ?", new byte[] {9}, logo.getId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_branding_source_revision")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + var sibling = binding(f, "1", CommandSource.SCOPE, commandUpsert("BRANDING_SIBLING")); + apply(f, sibling); + var inherited = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, sibling.commitId()) + .orElseThrow() + .branding() + .orElseThrow(); + assertThat(inherited.items()).isEqualTo(selected.items()); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.binding()).isEqualTo(sibling); + var deleted = + binding( + f, + "1", + BrandingSource.SCOPE, + BrandingSource.deletePayload("logo.png", BrandingSource.Role.LOGO)); + apply(f, deleted); + assertThat( + new BrandingSourceRepository(f.dsl) + .readSnapshot(f.target, deleted.commitId()) + .orElseThrow() + .roleDeclarations() + .values()) + .containsOnly("EMPTY"); + assertThat( + new BrandingSourceRepository(f.dsl) + .readSnapshot(f.target, first.commitId()) + .orElseThrow()) + .isEqualTo(selected); + } + + @Test + void retainedVersionCannotAcquireMissingBrandingGenesis() { + var f = fixture("58"); + var original = + binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(original); + coordinator.claimApplicationSlot(original); + coordinator.markOwnerInProgress( + original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var commands = + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); + var applied = commands.apply(original).orElseThrow(); + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-control-plane-command-application/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, original.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, applied.canonicalBytes()); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + original.commitId(), + original.digest(), + applied.resultIdentity(), + out.toByteArray(), + List.of(applied.commandAppliedEpoch())); + coordinator.recordOwnerOutcome(original, outcome); + coordinator.advanceVisibilityFence( + original, + new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); + commands.captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) + .captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(f.dsl) + .captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) + .captureSynchronized(original); + coordinator.releaseApplicationSlot(original); + }); + var originalBytes = + f.dsl + .fetchSingle( + "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, byte[].class); + var originalSources = + List.of("command_source", "realm_policy", "asset_source", "gameplay_rule"); + var sourceJson = + originalSources.stream() + .map( + name -> + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class)) + .toList(); + var fenceJson = + f.dsl + .fetchSingle( + "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class); + f.migrate(); + var historical = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, original.commitId()) + .orElseThrow(); + assertThat(historical.branding()).isEmpty(); + assertThat(historical.command().binding()).isEqualTo(original); + assertThat( + List.of( + historical.command().canonicalJson(), + historical.policy().canonicalJson(), + historical.asset().canonicalJson(), + historical.gameplay().canonicalJson())) + .isEqualTo(sourceJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class)) + .isEqualTo(fenceJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, byte[].class)) + .isEqualTo(originalBytes); + assertThatThrownBy( + () -> + f.tx.execute( + ignored -> new GameDesignSourceRepository(f.dsl).captureSynchronized(original))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + assertThat(new BrandingSourceRepository(f.dsl).readGenesis(f.target)).isEmpty(); + assertThatThrownBy( + () -> + f.tx.execute( + ignored -> new BrandingSourceRepository(f.dsl).enrollFreshDraft(f.target))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); + assertThatThrownBy(() -> new GameDesignSourceRepository(f.dsl).readGenesis(f.target)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + + @Test + void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { + var f = fixture(null); + var foreignGame = new Game(); + foreignGame.setTenantId(UUID.randomUUID().toString()); + foreignGame.setName("Foreign asset owner"); + var foreign = + Objects.requireNonNull( + f.tx.execute(ignored -> new GameRepository(f.dsl).save(foreignGame))); + var source = new GameAsset(); + source.setTenantId(foreign.getTenantId()); + source.setFileName("foreign.png"); + source.setContentType("image/png"); + source.setData(new byte[] {1}); + var foreignAsset = + Objects.requireNonNull( + f.tx.execute(ignored -> new GameAssetRepository(f.dsl).save(source))); + var payload = + BrandingSource.upsertPayload( + foreignAsset.getId().toString(), + "foreign.png", + BrandingSource.Role.FAVICON, + BrandingSource.Requiredness.REQUIRED); + var binding = binding(f, "0", BrandingSource.SCOPE, payload); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BRANDING_SOURCE_ROW_UNAVAILABLE"); + assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + } + + private void apply(Fixture f, DraftCommitBinding binding) { + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var sources = new GameDesignSourceRepository(f.dsl); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + } + + private static String commandUpsert(String commandId) { + return CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"" + + commandId + + "\",\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"); + } + + private DraftCommitBinding binding( + Fixture f, String epoch, String primaryScope, String... payloads) { + var revisions = new ArrayList(); + var scopes = new java.util.TreeSet(); + scopes.add(primaryScope); + for (int i = 0; i < payloads.length; i++) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + if (payloads[i].contains("\"revisionKind\":\"ASSET_REFERENCE\"")) + scopes.add(AssetSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"GAMEPLAY_RULE\"")) + scopes.add(GameplayRuleSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"COMMAND_DEFINITION\"")) + scopes.add(CommandSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"REALM_ENTRY_POLICY\"")) + scopes.add(net.firedevops.firemud.common.gamedesign.RealmPolicySource.SCOPE); + } + var units = + scopes.stream() + .map( + scope -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + f.target.canonicalVersionId().toString(), + scope, + "effective", + scope.equals(primaryScope) ? epoch : "0")) + .toList(); + return DraftCommitBinding.create( + f.target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", revisions, units); + } + + private GameAsset asset(Fixture f, String name) { + var asset = new GameAsset(); + asset.setTenantId(f.target.gameDesignVersionTenantKey()); + asset.setFileName(name); + asset.setContentType("image/png"); + asset.setData(name.getBytes(StandardCharsets.UTF_8)); + return Objects.requireNonNull( + f.tx.execute(ignored -> new GameAssetRepository(f.dsl).save(asset))); + } + + private Fixture fixture(String maximumMigration) { + var schema = "branding_source_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + var config = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (maximumMigration != null) config.target(maximumMigration); + config.load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(data)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Branding source storage fixture"); + var savedGame = + Objects.requireNonNull(tx.execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull( + tx.execute( + ignored -> { + if (maximumMigration == null) return new VersionRepository(dsl).save(version); + // Retained fixture intentionally uses the pre-branding producer, in its actual + // insert transaction. + long id = + dsl.fetchSingle( + "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, version_number, version_state, version_state_epoch, is_script_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', 1, 'DRAFT', 1, FALSE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING id", + savedGame.getTenantId(), + savedGame.getCanonicalTenantId(), + UUID.randomUUID(), + savedGame.getId(), + savedGame.getTenantId()) + .get(0, Long.class); + var retained = new VersionRepository(dsl).findById(id).orElseThrow(); + var oldTarget = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + id, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + var policy = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository( + dsl) + .recordFreshGenesis(oldTarget); + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + oldTarget, policy.receiptId(), policy.creationTransactionId())); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(dsl) + .enrollFreshDraft(oldTarget); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( + dsl) + .enrollFreshDraft(oldTarget); + return retained; + })); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, target, data, schema); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + DraftCommitBinding.TargetProof target, + DriverManagerDataSource data, + String schema) { + void migrate() { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + } + } +} 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 d8d340f0ff..dbea9e423f 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 @@ -25,7 +25,7 @@ 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; @@ -445,6 +445,10 @@ void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() assertThat(genesis.policy().receiptId()).isEqualTo(genesis.command().receiptId()); assertThat(genesis.asset().receiptId()).isNotEqualTo(genesis.policy().receiptId()); assertThat(genesis.asset().target()).isEqualTo(fixture.target()); + assertThat(genesis.brandingEvidence()).isPresent(); + assertThat(genesis.brandingEvidence().orElseThrow().target()).isEqualTo(fixture.target()); + assertThat(genesis.brandingEvidence().orElseThrow().creationTransactionId()) + .isEqualTo(genesis.policy().creationTransactionId()); assertThat(genesis.asset().creationTransactionId()) .isEqualTo(genesis.policy().creationTransactionId()); assertThat(genesis.policy().creationTransactionId()) @@ -768,12 +772,19 @@ void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { var read = fixture.sources().readCapture(operation).orElseThrow(); assertThat(retry.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); assertThat(retry.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(retry.branding()).isPresent(); + assertThat(retry.branding().orElseThrow().canonicalBytes()) + .containsExactly(first.branding().orElseThrow().canonicalBytes()); assertThat(read.command().canonicalBytes()).containsExactly(first.command().canonicalBytes()); assertThat(read.policy().canonicalBytes()).containsExactly(first.policy().canonicalBytes()); + assertThat(read.branding().orElseThrow().canonicalBytes()) + .containsExactly(first.branding().orElseThrow().canonicalBytes()); assertThat(read.command().snapshot().binding()) .isEqualTo(operation.account().input().selection().selectedCommit()); assertThat(read.policy().snapshot().binding()) .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(read.branding().orElseThrow().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); } private static GameDesignSourceRepository.Application apply( @@ -943,8 +954,7 @@ private static String command(String id, String alias) { + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + "\"aliases\":[\"" + alias - + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," - + "\"legacyExtension\":{\"kept\":true}}"; + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"; } private static Fixture fixture() { 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 77b644edbc..717f8af68e 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 @@ -21,7 +21,7 @@ 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.CommandSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyApplication; @@ -273,7 +273,7 @@ void sourceComposesOneOwnerResultAndCommandOnlyFenceInheritsPolicy() { + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," - + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}")); + + "\"effects\":[]}")); var commandScope = new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -1010,7 +1010,7 @@ private static DraftCommitBinding commandOnlyBinding( + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," - + "\"effects\":[],\"legacyExtension\":{\"kept\":true}}"))), + + "\"effects\":[]}"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index c8f2599079..9a1d97347c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -29,7 +29,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; -import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index d8eea4bfd0..3f03c10adf 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -677,7 +677,7 @@ void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactR .isEqualTo(first)); assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) .isEqualTo(1L); - var sibling = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + var sibling = binding(f, commandUpsert("TEMPLATE_SIBLING"), CommandSource.SCOPE, "0"); apply(f, sibling); assertThat(source(f, sibling).entries()).isEqualTo(first.entries()); assertThat(source(f, sibling).sourceEpoch()).isEqualTo("1"); @@ -829,7 +829,7 @@ void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { .fetchSingle("SELECT default_version_id FROM game_templates WHERE id = ?", legacy) .get(0, Long.class)) .isNull(); - var selected = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + var selected = binding(f, commandUpsert("TEMPLATE_SELECTED"), CommandSource.SCOPE, "0"); apply(f, selected); assertThat(source(f, selected).entries()).isEmpty(); assertThatThrownBy( @@ -847,7 +847,7 @@ void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { @Test void newCaptureCannotIgnorePendingUnqualifiedExplicitTargetRow() { var f = fixture(); - var selected = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + var selected = binding(f, commandUpsert("TEMPLATE_BLOCKED"), CommandSource.SCOPE, "0"); assertThatThrownBy( () -> f.tx.executeWithoutResult( @@ -1357,6 +1357,16 @@ private DraftCommitBinding binding(Fixture f, String payload, String scope, Stri Map.of(scope, epoch)); } + private static String commandUpsert(String commandId) { + return CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"" + + commandId + + "\",\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"); + } + private DraftCommitBinding binding( Fixture f, List revisions, Map scopes) { var units = diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java new file mode 100644 index 0000000000..ef7ac23699 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import org.junit.jupiter.api.Test; + +class BrandingSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void everyRoleRetainsItsExactBindingAndRequiredPolicy() { + for (var role : BrandingSource.Role.values()) { + var binding = + binding( + BrandingSource.upsertPayload( + "1", "image.png", role, BrandingSource.Requiredness.REQUIRED)); + var reference = BrandingSource.replay(List.of(), binding).references().getFirst(); + assertThat(reference.role()).isEqualTo(role); + assertThat(reference.family()).isEqualTo("BRANDING"); + assertThat(reference.sourceBinding()).isSameAs(binding); + assertThatThrownBy( + () -> + BrandingSource.upsertPayload( + "1", "image.png", role, BrandingSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void replayPreservesUntouchedOriginalRevisionAndExplicitRoleDeclarations() { + var original = + binding( + BrandingSource.upsertPayload( + "1", "logo.png", BrandingSource.Role.LOGO, BrandingSource.Requiredness.REQUIRED)); + var first = BrandingSource.replay(List.of(), original); + var changed = + binding( + BrandingSource.upsertPayload( + "2", "theme.css", BrandingSource.Role.THEME, BrandingSource.Requiredness.REQUIRED)); + var replay = BrandingSource.replay(first.references(), changed); + assertThat(replay.references().getFirst().sourceBinding()).isEqualTo(original); + var items = + replay.references().stream() + .map( + r -> + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( + r, "image/png", "sha256:" + "a".repeat(64), 1)) + .toList(); + var snapshot = + new BrandingSourceSnapshot(changed, "2", original.commitId(), UUID.randomUUID(), items); + assertThat(snapshot.roleDeclarations()) + .isEqualTo( + Map.of("RESOURCE", "EMPTY", "LOGO", "PRESENT", "FAVICON", "EMPTY", "THEME", "PRESENT")); + assertThat(BrandingSourceSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThatThrownBy( + () -> + BrandingSourceSnapshot.fromStored( + snapshot + .canonicalJson() + .replace("\"FAVICON\":\"EMPTY\"", "\"FAVICON\":\"PRESENT\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownMalformedOptionalAndOrdinaryReinterpretationDeny() { + String payload = + BrandingSource.upsertPayload( + "1", "logo.png", BrandingSource.Role.LOGO, BrandingSource.Requiredness.REQUIRED); + for (String invalid : + List.of( + payload.replace("LOGO", "UNKNOWN"), + payload.replace("REQUIRED", "OPTIONAL"), + payload.replace("BRANDING_ASSET_REFERENCE", "UNKNOWN"), + payload.replace("\"family\":\"BRANDING\"", "\"family\":\"ORDINARY\""), + payload.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + payload + "{}")) { + assertThatThrownBy(() -> BrandingSource.mutations(binding(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + BrandingSource.replay( + List.of(), + binding( + BrandingSource.upsertPayload( + "1", + "a", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED), + BrandingSource.upsertPayload( + "1", + "b", + BrandingSource.Role.THEME, + BrandingSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void knownSiblingDispatchPreservesFullBindingWithoutAcceptingUnknownKinds() { + var binding = + binding( + BrandingSource.deletePayload("logo.png", BrandingSource.Role.LOGO), + AssetSource.deletePayload("ordinary.png")); + assertThat(BrandingSource.mutations(binding)).hasSize(1); + assertThat(AssetSource.mutations(binding)).hasSize(1); + assertThat(CommandSource.mutations(binding)).isEmpty(); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isFalse(); + assertThat(GameplayRuleSource.mutations(binding)).isEmpty(); + assertThat(BrandingSource.mutations(binding).getFirst().binding()).isSameAs(binding); + } + + private static DraftCommitBinding binding(String... payloads) { + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + BrandingSource.SCOPE, + VERSION.toString(), + BrandingSource.SCOPE, + "effective", + "0"))); + } +} 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 index 771254360e..d09291b4e8 100644 --- 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 @@ -9,7 +9,7 @@ import net.firedevops.firemud.common.authoring.DraftBaseReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.publication.AssetSnapshot; -import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; import org.junit.jupiter.api.Test; 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 9295f3f809..60957327e4 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 @@ -16,7 +16,7 @@ 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; @@ -296,8 +296,7 @@ private static String command(String id, String alias) { + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + "\"aliases\":[\"" + alias - + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]," - + "\"legacyExtension\":{\"kept\":true}}"; + + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"; } private static DraftCommitBinding.RevisionPayload revision( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java new file mode 100644 index 0000000000..233a1123c8 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java @@ -0,0 +1,238 @@ +package 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.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.Test; + +class GameDesignSelectedOwnerIntakeSourceGrpcServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void authenticatesAccountPeerAndRejectsMalformedOrMismatchedInputBeforeOwnerRead() { + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var valid = request(Owner.ENTITY_MANAGEMENT); + var malformed = valid.toBuilder().setSchemaVersion(0).build(); + + var absentPeer = new Collector(); + service.readSelectedSource(malformed, absentPeer); + assertThat(absentPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + String[][] identities = { + {"test", "game-design-service"}, + {"other", "account-service"}, + {"test", "world-management-service"} + }; + for (String[] identity : identities) { + var denied = new Collector(); + peer(identity[0], identity[1]).run(() -> service.readSelectedSource(valid, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + var malformedResult = new Collector(); + peer(NAMESPACE, "account-service") + .run(() -> service.readSelectedSource(malformed, malformedResult)); + assertThat(malformedResult.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var wrongNamespace = new Collector(); + peer(NAMESPACE, "account-service") + .run( + () -> + service.readSelectedSource( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("123", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(valid, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + verifyNoInteractions(owner); + } + + @Test + void rejectsChangedRequestFieldsUnknownFieldsAndOversizedWireBeforeOwnerRead() { + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var valid = request(Owner.AUTOMATION_SCRIPTING); + var changedReader = valid.toBuilder().setIntendedReader("spiffe://wrong").build(); + var changedPurpose = valid.toBuilder().setPurpose("OTHER_PURPOSE").build(); + var unknown = + valid.toBuilder() + .mergeUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + var oversized = + valid.toBuilder() + .setPreliminarySourceScope( + ByteString.copyFrom(new byte[SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES])) + .build(); + + for (var invalid : List.of(changedReader, changedPurpose, unknown, oversized)) { + var result = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(invalid, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoAndActualCompleteExportForBothOwnerScopes() { + var selected = + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command")); + for (Owner ownerType : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = SelectedOwnerIntakeSourceExportTest.scope(ownerType, selected); + var export = + SelectedOwnerIntakeSourceExport.create( + scope, SelectedOwnerIntakeSourceExportTest.sources(selected, "0")); + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(owner.readSource(any())).thenReturn(export); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var request = request(scope); + var result = new Collector(); + + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(request, result)); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(request); + var decodedRequest = SelectedOwnerIntakeSourceProtoCodec.fromRequest(request); + var content = + SelectedOwnerIntakeSourceProtoCodec.fromResponse(decodedRequest, result.response); + assertThat(content.canonicalBytes()).isEqualTo(export.canonicalBytes()); + assertThat(content.digest()).isEqualTo(export.digest()); + verify(owner).readSource(scope); + } + } + + @Test + void deniesAbsentOrMismatchedExportAndSanitizesOwnerFailures() { + var scope = + SelectedOwnerIntakeSourceExportTest.scope( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command"))); + var request = request(scope); + + var missingOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(missingOwner.readSource(scope)).thenReturn(null); + assertFailure(missingOwner, request, Status.Code.FAILED_PRECONDITION); + + var differentScope = + SelectedOwnerIntakeSourceExportTest.scope( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + CommandSource.deletePayload("absent-command"))); + var differentExport = + SelectedOwnerIntakeSourceExport.create( + differentScope, + SelectedOwnerIntakeSourceExportTest.sources(differentScope.selected(), "0")); + var mismatchedOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(mismatchedOwner.readSource(scope)).thenReturn(differentExport); + assertFailure(mismatchedOwner, request, Status.Code.FAILED_PRECONDITION); + + var failingOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(failingOwner.readSource(scope)) + .thenThrow(Status.UNAVAILABLE.withDescription("private owner detail").asRuntimeException()); + var failure = invoke(failingOwner, request); + assertThat(failure.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(failure.errorDescription).isNull(); + assertThat(failure.response).isNull(); + } + + private static void assertFailure( + GameDesignSelectedOwnerIntakeSourceReadService owner, + SelectedOwnerIntakeSourceRequest request, + Status.Code code) { + var result = invoke(owner, request); + assertThat(result.error).isEqualTo(code); + assertThat(result.response).isNull(); + } + + private static Collector invoke( + GameDesignSelectedOwnerIntakeSourceReadService owner, + SelectedOwnerIntakeSourceRequest request) { + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var result = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(request, result)); + return result; + } + + private static SelectedOwnerIntakeSourceRequest request(Owner owner) { + var selected = + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command")); + return request(SelectedOwnerIntakeSourceExportTest.scope(owner, selected)); + } + + private static SelectedOwnerIntakeSourceRequest request( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope) { + return SelectedOwnerIntakeSourceProtoCodec.toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope)); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + String errorDescription; + SelectedOwnerIntakeSourceResponse response; + boolean completed; + + @Override + public void onNext(SelectedOwnerIntakeSourceResponse value) { + response = value; + } + + @Override + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + errorDescription = Status.fromThrowable(value).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..6d079a3010 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameDesignSelectedOwnerIntakeSourceReadServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final UUID GENESIS = UUID.randomUUID(); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void readsCompleteSelectedSourceForEntityAndAutomationOnlyAfterExactPermission() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + org.mockito.Mockito.doAnswer( + invocation -> new SelectedOwnerIntakeSourceReadEvidence(invocation.getArgument(0))) + .when(permissions) + .read(any()); + + var binding = binding(); + var scope = scope(owner, binding); + var export = SelectedOwnerIntakeSourceExport.create(scope, sources(binding)); + when(repository.requireSelectedOwnerIntakeSource(scope)).thenReturn(export); + var service = service(repository, transactions, permissions); + + var result = + new java.util.concurrent.atomic.AtomicReference(); + asAccount(() -> result.set(service.readSource(scope))); + + assertThat(result.get()).isSameAs(export); + assertThat(result.get().scope().canonicalBytes()).isEqualTo(scope.canonicalBytes()); + assertThat(result.get().scope().digest()).isEqualTo(scope.digest()); + assertThat(result.get().canonicalBytes()).isNotEmpty(); + assertThat(result.get().digest()).isNotBlank(); + var ordered = org.mockito.Mockito.inOrder(permissions, transactions, repository); + ordered.verify(permissions).read(any()); + ordered.verify(transactions).getTransaction(any()); + ordered.verify(repository).requireSelectedOwnerIntakeSource(scope); + } + } + + @Test + void rejectsMissingOrSubstitutedPermissionBeforeOpeningTheSourceTransaction() { + var binding = binding(); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding); + + assertPermissionDeniedBeforeQuery(scope, null); + assertPermissionDeniedBeforeQuery( + scope, + request -> + new SelectedOwnerIntakeSourceReadEvidence( + new SelectedOwnerIntakeSourceReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.intendedReader(), + request.purpose(), + request.scope()))); + assertPermissionDeniedBeforeQuery( + scope, + request -> + new SelectedOwnerIntakeSourceReadEvidence( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + request.targetNamespace(), + scope(Owner.AUTOMATION_SCRIPTING, request.scope().selected())))); + } + + @Test + void authenticatesAccountPeerAndRejectsEndUserContextBeforePermissionOrStorage() { + var scope = scope(Owner.ENTITY_MANAGEMENT, binding()); + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> service.readSource(scope)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + asPeer("spiffe://firemud/ns/test/sa/game-design-service", () -> denied(service, scope)); + asPeer("spiffe://firemud/ns/other/sa/account-service", () -> denied(service, scope)); + SessionContext.setContext("123", List.of(), java.util.Map.of()); + asAccount(() -> denied(service, scope)); + assertNoPermissionOrQuery(permissions, transactions, repository); + } + + @Test + void rejectsNamespaceMismatchAndAmbientTransactionOrSynchronizationBeforePermission() { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + var service = service(repository, transactions, permissions); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding()); + var wrongNamespace = + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + "other", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + scope.selected()); + + asAccount(() -> denied(service, wrongNamespace)); + TransactionSynchronizationManager.setActualTransactionActive(true); + asAccount(() -> denied(service, scope)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + asAccount(() -> denied(service, scope)); + assertNoPermissionOrQuery(permissions, transactions, repository); + } + + @Test + void rejectsRepositoryExportForAnotherExactScope() { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + org.mockito.Mockito.doAnswer( + invocation -> new SelectedOwnerIntakeSourceReadEvidence(invocation.getArgument(0))) + .when(permissions) + .read(any()); + var binding = binding(); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding); + var substitutedScope = + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + NAMESPACE, + UUID.randomUUID(), + scope.fenceId(), + scope.intakeRequestId(), + scope.actorAccountId(), + binding); + when(repository.requireSelectedOwnerIntakeSource(scope)) + .thenReturn(SelectedOwnerIntakeSourceExport.create(substitutedScope, sources(binding))); + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> asAccount(() -> service.readSource(scope))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verify(permissions).read(any()); + org.mockito.Mockito.verify(transactions).getTransaction(any()); + org.mockito.Mockito.verify(repository).requireSelectedOwnerIntakeSource(scope); + } + + private static void assertPermissionDeniedBeforeQuery( + SelectedOwnerIntakeSourceReadScope scope, + java.util.function.Function< + SelectedOwnerIntakeSourceReadEvidence.Request, SelectedOwnerIntakeSourceReadEvidence> + response) { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + if (response == null) { + org.mockito.Mockito.doReturn(null).when(permissions).read(any()); + } else { + org.mockito.Mockito.doAnswer(invocation -> response.apply(invocation.getArgument(0))) + .when(permissions) + .read(any()); + } + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> asAccount(() -> service.readSource(scope))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verify(permissions).read(any()); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + } + + private static void assertNoPermissionOrQuery( + Object permissions, Object transactions, Object repository) { + org.mockito.Mockito.verifyNoInteractions(permissions, transactions, repository); + } + + private static void denied( + GameDesignSelectedOwnerIntakeSourceReadService service, + SelectedOwnerIntakeSourceReadScope scope) { + assertThatThrownBy(() -> service.readSource(scope)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + + private static GameDesignSelectedOwnerIntakeSourceReadService service( + GameDesignSourceRepository repository, + PlatformTransactionManager transactions, + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + permissions) { + return new GameDesignSelectedOwnerIntakeSourceReadService( + repository, transactions, permissions, NAMESPACE); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + var policy = new RealmPolicySnapshot(binding, "0", List.of()); + var asset = new AssetSnapshot(binding, "0", null, GENESIS, List.of()); + var gameplay = new GameplayRuleSnapshot(binding, "0", null, GENESIS, List.of()); + var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); + var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + target.canonicalVersionId().toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void asAccount(Runnable action) { + asPeer(ACCOUNT_PEER, action); + } + + private static void asPeer(String uri, Runnable action) { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()) + .run(action); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java new file mode 100644 index 0000000000..4fe0d656c0 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -0,0 +1,228 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +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.CommandSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeSourceExportTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @Test + void framesTheScopeAndAllSixFamiliesInFixedOrder() { + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected); + var sources = sources(selected, "0"); + var export = SelectedOwnerIntakeSourceExport.create(scope, sources); + + var expected = new ByteArrayOutputStream(); + frame(expected, SelectedOwnerIntakeSourceExport.DOMAIN); + frame(expected, scope.canonicalBytes()); + frame(expected, scope.digest()); + frameFamily(expected, "COMMAND", sources.command().canonicalBytes()); + frameFamily(expected, "REALM_POLICY", sources.policy().canonicalBytes()); + frameFamily(expected, "ASSET", sources.asset().canonicalBytes()); + frameFamily(expected, "GAMEPLAY_RULE", sources.gameplay().canonicalBytes()); + frameFamily(expected, "BRANDING", sources.branding().orElseThrow().canonicalBytes()); + frameFamily( + expected, "TEMPLATE_CONFIG", sources.templateConfig().orElseThrow().canonicalBytes()); + + assertThat(export.canonicalBytes()).isEqualTo(expected.toByteArray()); + assertThat(export.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(expected.toByteArray())); + assertThat(export.sources()).isSameAs(sources); + assertThat(export.scope()).isEqualTo(scope); + } + + @Test + void sharedConsumerDecodesExactCompleteExportsForBothOwners() { + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner, selected); + var sources = sources(selected, "0"); + var exported = SelectedOwnerIntakeSourceExport.create(scope, sources); + + var content = + SelectedOwnerIntakeSourceContent.fromStored( + exported.canonicalBytes(), scope, exported.digest()); + + assertThat(content.scope()).isEqualTo(scope); + assertThat(content.canonicalBytes()).isEqualTo(exported.canonicalBytes()); + assertThat(content.digest()).isEqualTo(exported.digest()); + assertThat(content.snapshotBytes("COMMAND")).isEqualTo(sources.command().canonicalBytes()); + assertThat(content.snapshotBytes("REALM_POLICY")) + .isEqualTo(sources.policy().canonicalBytes()); + assertThat(content.snapshotBytes("ASSET")).isEqualTo(sources.asset().canonicalBytes()); + assertThat(content.snapshotBytes("GAMEPLAY_RULE")) + .isEqualTo(sources.gameplay().canonicalBytes()); + assertThat(content.snapshotBytes("BRANDING")) + .isEqualTo(sources.branding().orElseThrow().canonicalBytes()); + assertThat(content.snapshotBytes("TEMPLATE_CONFIG")) + .isEqualTo(sources.templateConfig().orElseThrow().canonicalBytes()); + assertThat(content.gameplaySource().binding()).isEqualTo(selected); + assertThat(content.templateConfigSource().binding()).isEqualTo(selected); + } + } + + @Test + void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); + var first = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), sources(selected, "0")); + var replay = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), sources(selected, "0")); + byte[] exposed = first.canonicalBytes(); + exposed[0] ^= 0x7f; + + assertThat(first.canonicalBytes()).isEqualTo(replay.canonicalBytes()); + assertThat(first.digest()).isEqualTo(replay.digest()); + } + + @Test + void rejectsDifferentSelectedBindingAndChangedFamilyContent() { + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); + var sources = sources(selected, "0"); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope( + Owner.ENTITY_MANAGEMENT, + binding( + id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + CommandSource.deletePayload("absent-command"))), + sources)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("COMMAND"); + + var original = + SelectedOwnerIntakeSourceExport.create(scope(Owner.ENTITY_MANAGEMENT, selected), sources); + var changed = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "1")); + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(changed.digest()).isNotEqualTo(original.digest()); + } + + @Test + void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); + var complete = sources(selected, "0"); + var missingBranding = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + Optional.empty(), + complete.templateConfig()); + var missingTemplate = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + complete.branding(), + Optional.empty()); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), missingBranding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("branding"); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), missingTemplate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("template-config"); + } + + @Test + void rejectsExportLargerThanEightMib() { + var selected = binding(COMMIT, "x".repeat(1_400_000)); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "0"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("8 MiB"); + } + + static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding, String commandEpoch) { + var command = + new CommandSnapshot(binding, commandEpoch, null, "sha256:" + "a".repeat(64), List.of()); + var policy = new RealmPolicySnapshot(binding, "0", List.of()); + var asset = new AssetSnapshot(binding, "0", null, GENESIS, List.of()); + var gameplay = new GameplayRuleSnapshot(binding, "0", null, GENESIS, List.of()); + var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); + var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + static SelectedOwnerIntakeSourceReadScope scope(Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST, + commitId, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frameFamily(ByteArrayOutputStream out, String family, byte[] bytes) { + frame(out, family); + frame(out, bytes); + frame(out, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} From 14963871338504af0f20376a38ba0b0e68a280d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:08:07 +1300 Subject: [PATCH 02/36] Prepare selected source migration after activation frontier --- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 +- ...cted_owner_intake_source_reservations.sql} | 0 ...rceReservationPostgresIntegrationTest.java | 55 ++++++++++++++----- .../AccountControlUiOwnerSourcesFixture.java | 4 +- ...urceDisclosurePostgresIntegrationTest.java | 6 +- 6 files changed, 49 insertions(+), 20 deletions(-) rename services/account-service/src/main/resources/db/migration/{V1006__selected_owner_intake_source_reservations.sql => V1007__selected_owner_intake_source_reservations.sql} (100%) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d5b9068bdb..dc7efcd4f1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1006. It preserves the actual V1005 combined parent and prior protection/disposal guards. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. +The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Prepared PostgreSQL upgrade and disclosure compositions have not run. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a309fa61f7..a47c51fb64 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation -The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1006 follows the actual V1005 plus Saga parent; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof retains parent rows, source bytes, history and xmin, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. +The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. ### Original StartSession protected activation source diff --git a/services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql b/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1006__selected_owner_intake_source_reservations.sql rename to services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index 7a21673b7b..3fd2c4dd1d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -14,10 +14,10 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; -/** PostgreSQL installation proof for V1006's additive selected-owner source reservations. */ +/** PostgreSQL installation proof for V1007's additive selected-owner source reservations. */ class AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest { @Test - void installsV1006OverCombinedV1005ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() { + void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() { var fixture = new AccountPostgresIntegrationFixture(); try { fixture.start(); @@ -28,12 +28,12 @@ void installsV1006OverCombinedV1005ParentGuardsAndRejectsMalformedReservationWit DriverManagerDataSource source = fixture.dataSource(schema); JdbcTemplate jdbc = new JdbcTemplate(source); - migration(source, schema, "1005").migrate(); - assertVersionApplied(jdbc, schema, "1005"); - for (String version : List.of("137", "159", "160.1", "1000", "1001", "1002", "1003")) { + migration(source, schema, "1006").migrate(); + assertVersionApplied(jdbc, schema, "1006"); + for (String version : List.of("137", "159", "160.1", "1000", "1001", "1002", "1003", "1004", "1004.1", "1004.2", "1004.3", "1005")) { assertVersionApplied(jdbc, schema, version); } - assertVersionNotApplied(jdbc, schema, "1006"); + assertVersionNotApplied(jdbc, schema, "1007"); var ownerDsl = org.jooq.impl.DSL.using( new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy(source), org.jooq.SQLDialect.POSTGRES); @@ -47,28 +47,41 @@ void installsV1006OverCombinedV1005ParentGuardsAndRejectsMalformedReservationWit account.setRole("player"); var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(ownerDsl); assertThat(ownerTransaction.execute(status -> accounts.save(account))).isNotNull(); + seedRetainedCombinedParentRows(jdbc); var retainedParent = retainedParentRows(jdbc); - String historyQuery = "SELECT installed_rank || ':' || version || ':' || script || ':' " - + "|| checksum || ':' || success FROM flyway_schema_history " - + "WHERE version IS NOT NULL AND version <> '1006' ORDER BY installed_rank"; + assertThat(retainedParent.values()).allSatisfy(rows -> assertThat(rows).isNotEmpty()); + String historyQuery = + "SELECT jsonb_build_object('row', to_jsonb(h), 'xmin', h.xmin::TEXT)::TEXT " + + "FROM flyway_schema_history h WHERE version IS NULL OR version <> '1007' " + + "ORDER BY installed_rank"; var retainedHistory = jdbc.queryForList(historyQuery, String.class); var protectionsGuard = functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])"); var disposalGuard = functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()"); + var disposalWriterGuard = functionDefinition(jdbc, "account_initial_gameplay_login_writer_guard()"); + var alignmentGuard = functionDefinition(jdbc, "account_ss_activation_settlement_insert_guard()"); + assertThat(alignmentGuard).contains( + "terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); assertThat(protectionsGuard).contains("account_start_session_admission_protections", "account_start_session_activation_protections"); assertWorldSourceExclusionGuards( functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"), functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"), functionDefinition(jdbc, "account_hosted_terms_disclosure_handoff_guard()")); - migration(source, schema, "1006").migrate(); - assertVersionApplied(jdbc, schema, "1005"); + Flyway upgrade = migration(source, schema, "1007"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); assertVersionApplied(jdbc, schema, "1006"); + assertVersionApplied(jdbc, schema, "1007"); assertThat(jdbc.queryForList(historyQuery, String.class)).isEqualTo(retainedHistory); assertThat(retainedParentRows(jdbc)).isEqualTo(retainedParent); assertThat(functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])")) .isEqualTo(protectionsGuard); assertThat(functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()")) .isEqualTo(disposalGuard); + assertThat(functionDefinition(jdbc, "account_initial_gameplay_login_writer_guard()")) + .isEqualTo(disposalWriterGuard); + assertThat(functionDefinition(jdbc, "account_ss_activation_settlement_insert_guard()")) + .isEqualTo(alignmentGuard); assertInstalledOwnerReservationSchema(jdbc, schema); String holdGuard = @@ -114,10 +127,26 @@ private static Flyway migration( .load(); } - /** Exact physical parent Account and its real source baselines; no credential authority implied. */ + private static void seedRetainedCombinedParentRows(JdbcTemplate jdbc) { + Long sagaId = jdbc.queryForObject( + "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", + Long.class, "retained-selected-source-upgrade", "PENDING"); + jdbc.update( + "INSERT INTO saga_step(instance_id, name, status, attempt) VALUES (?, ?, ?, ?)", + sagaId, "retained-step", "PENDING", 3); + jdbc.update( + "INSERT INTO account_initial_gameplay_login_disposals(request_id, disposal_operation_id, " + + "caller_workload, caller_context_id, disposal_digest, witness_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?)", + UUID.randomUUID(), UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service", UUID.randomUUID(), + "a".repeat(64), "retained parent disposal witness".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + /** Exact parent Account/source, disposal and Saga rows; no credential authority implied. */ private static Map> retainedParentRows(JdbcTemplate jdbc) { Map> rows = new java.util.LinkedHashMap<>(); - for (String table : List.of("accounts", "account_authority_source_records")) { + for (String table : List.of("accounts", "account_authority_source_records", "account_initial_gameplay_login_disposals", "saga_instance", "saga_step")) { rows.put(table, jdbc.queryForList("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + table + " t ORDER BY to_jsonb(t)::TEXT", String.class)); } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 7910399321..1d189ebf74 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -134,9 +134,9 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { - if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget)) { + if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention or 1006 source-disclosure frontier is supported"); + "Only the preserved 160.1 source-retention, 1006 parent or 1007 source-disclosure frontier is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index a7855c56a8..2a0d902762 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -61,7 +61,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Actual Account V1006 preliminary permission and independent GD six-family disclosure owners. + * Actual Account V1007 preliminary permission and independent GD six-family disclosure owners. * Creator, environment, PKI, selected author admission/readbacks and authored inputs are controlled; * no final intake authorization, recipient retention, genuine provenance or registration is proved. */ @@ -87,10 +87,10 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu try (var fixture = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), ACCOUNT.getUsername(), ACCOUNT.getPassword(), REDIS.getHost(), REDIS.getMappedPort(6379), temporary.resolve("account"), local.binding().target().canonicalTenantId(), - Clock.systemUTC(), "1006")) { + Clock.systemUTC(), "1007")) { var issued = fixture.preparedOriginalCreator(); var f = issued.sources(); - assertThat(f.dsl.fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version IN ('1007','1008','1009')").get(0, Integer.class)).isZero(); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version IN ('1008','1009','1010')").get(0, Integer.class)).isZero(); retainControlledSelectedAuthorAdmission(issued, local.binding()); var reservations = new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), f.manager, NAMESPACE); From 02e4c2da461051175d18df11fbe380040d3fb130 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:41:29 +1300 Subject: [PATCH 03/36] Recognize Branding sibling in complete source policy capture --- .../gamedesign/publication/RealmPolicySource.java | 2 ++ .../gamedesign/publication/RealmPolicySourceTest.java | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) 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 d68490f253..fa17a46d6b 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 @@ -11,6 +11,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import tools.jackson.databind.JsonNode; @@ -74,6 +75,7 @@ public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind) + || BrandingSource.REVISION_KIND.equals(kind) || net.firedevops.firemud.common.gamedesign.GameplayRuleSource.REVISION_KIND.equals(kind) || TemplateConfigSource.REVISION_KIND.equals(kind)) return false; 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 index 0a57425128..8b6ce635ef 100644 --- 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 @@ -8,6 +8,7 @@ import java.util.stream.IntStream; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; @@ -29,12 +30,18 @@ void policyClassifierRecognizesKnownSiblingOwnersAndRejectsUnknownKinds() { AssetSource.upsertPayload("41", "map", AssetSource.Requiredness.REQUIRED)); var template = policyRevision("3", UUID.randomUUID(), TemplateConfigSource.deletePayload("7")); - var unknown = policyRevision("4", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); + var branding = + policyRevision( + "4", + UUID.randomUUID(), + "{\"revisionKind\":\"" + BrandingSource.REVISION_KIND + "\"}"); + var unknown = policyRevision("5", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); assertThat(RealmPolicySource.isPolicyRevision(policy)).isTrue(); assertThat(RealmPolicySource.isPolicyRevision(command)).isFalse(); assertThat(RealmPolicySource.isPolicyRevision(asset)).isFalse(); assertThat(RealmPolicySource.isPolicyRevision(template)).isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(branding)).isFalse(); assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(unknown)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported Game Design owner revision kind"); From 6eca3679cdc5d147716b837ec34bbd580e4e6e0a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:51:31 +1300 Subject: [PATCH 04/36] docs: carry R21 selected release proof attribution --- .../game-authoring-publishing-and-activation.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 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 3d1e92c778..339c2ee242 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -14,15 +14,13 @@ The same closure prepares the actual Game Design original launch-descriptor and This read-stage preparation also carries the strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and a class-only guarded World fixture. The eight prepared code paths comprise the two shared models and their focused proofs, the World lifecycle reader and its unit proof, the guarded native fixture and its class-only build export. These postimages are source-prepared and unqualified; no factory execution or passing fresh writer/readback is claimed. Actual Game Design writer/storage integration and five-store proof remain in the full selected-owner successor. Public fresh/PENDING publication remains default-denied; no registration, activation or genuine creator, issuer, environment, release or continuous-protection authority is granted. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused. -Qualification remains partial. R20 runs two focused native classes: all three Game Session authored-core cases pass with zero skips, while the 12-case Game Design Template configuration class has two failures and zero skips. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. These three focused cases do not constitute a fresh execution of all 325 Game Session native cases. +Qualification remains partial. R21's focused gate freshly passes all 12 Game Design Template configuration cases with zero skips; the three Game Session authored-core cases retain their R20 pass and also pass in R21's fresh unfiltered native execution. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. Game Design now proves first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance using a real visible public-production `REALM_ENTRY_POLICY` mutation before its complete World-only successor. Upstream Account and World inputs remain stipulated component evidence; these tests do not establish genuine authority. -The two Game Design cases reach first selected-owner reservation and correctly fail the full-Version requirement for one visible public-production realm policy. Their corrected fixture adds a real `REALM_ENTRY_POLICY` mutation and exact affected-scope epoch to each original Game Design binding. The actual source owner applies it before the complete World-only successor inherits the selected source. The first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance remain under test. Upstream Account and World inputs remain stipulated component evidence. Command and asset genesis, current selected snapshots and the qualified Template row are retained; the publication policy requirement is unchanged. +Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite. -Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections retain their passing native attribution. +R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in this invocation. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining independent static and Game Design cross-service gates are pending; full-native qualification remains held. -R20's full gate does not execute after the focused failure. The latest unfiltered R19 invocation executes 159 Game Design native cases with two failures and 325 Game Session native cases with one failure; it does not execute Game Design cross-service tests. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. The corrected focused and required unfiltered gates remain pending. - -The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown, and none of the nine fresh native failures is a connection refusal. This does not establish a repair of the intermittent R15/R16 refusal: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. No readiness-policy or host-settings change is selected. A subsequent canonical gate remains pending; failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). +The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). ### Original Account-ordered World source caller From dc208f6a0948619a93b2f68a36fe4700acfba02a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:00:33 +1300 Subject: [PATCH 05/36] test: carry safe retention trigger extraction and cross proof --- .../game-authoring-publishing-and-activation.md | 4 ++-- .../CanonicalInitialAdmissionRepositoryIntegrationTest.java | 2 +- 2 files changed, 3 insertions(+), 3 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 339c2ee242..c49af2fead 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 @@ -18,9 +18,9 @@ Qualification remains partial. R21's focused gate freshly passes all 12 Game Des Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite. -R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in this invocation. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining independent static and Game Design cross-service gates are pending; full-native qualification remains held. +R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in that invocation. R22 independently executes all 25 Game Design cross-service cases with zero failures, errors or skips and passes the previously missing Game Design static checks, formatting and documentation gates. Its only build failure is a nullable generic SQL extraction in the Game Session V1013 foreign-key test helper; a typed read preserves the exact trigger assertions, with its affected static recheck pending. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining Game Session static checks pass apart from that single helper finding; full-native qualification remains held. -The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). +The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. R22 passively captures all ten exact run-owned PostgreSQL lifecycles with no ownership gaps or observer errors; its passing cross-service run does not reproduce the refusal. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). ### Original Account-ordered World source caller diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index fbc3afa0eb..670e0fa2d3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -1522,7 +1522,7 @@ private static void assertV1013RetentionLaunchForeignKey(Fixture fixture) { + "AND launch_trigger.tgrelid = parent.oid ORDER BY launch_trigger.tgtype"); assertThat(launchTriggers).hasSize(2); assertThat(launchTriggers) - .extracting(row -> ((Number) row.get("tgtype")).intValue()) + .extracting(row -> row.get("tgtype", Integer.class)) .containsExactly(9, 17); assertThat(launchTriggers) .allSatisfy( From 0f97843a36e6eafde8597f56b1355eaa434c092f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:49:40 +1300 Subject: [PATCH 06/36] test: align selected source proofs with current owner APIs --- ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 2 + .../DraftAuthorizationFenceRepository.java | 20 +- ...tSelectedOwnerIntakeSourceReadService.java | 5 - ...rceReservationPostgresIntegrationTest.java | 91 ++-- .../AccountControlUiOwnerSourcesFixture.java | 12 +- ...electedOwnerIntakeClientLifecycleTest.java | 13 +- .../GameDesignSourceRepository.java | 66 +-- .../SelectedOwnerIntakeSourceExport.java | 7 +- .../PublishedReleaseBundleRepository.java | 2 +- ...urceDisclosurePostgresIntegrationTest.java | 408 ++++++++++++++---- ...BrandingSourcePostgresIntegrationTest.java | 7 +- ...meDesignSourcePostgresIntegrationTest.java | 2 +- ...lmPolicySourcePostgresIntegrationTest.java | 2 +- ...StorageUpgradePostgresIntegrationTest.java | 2 +- .../GameDesignReviewedBaseEvidenceTest.java | 2 +- .../publication/CommandSourceTest.java | 2 +- ...ectedOwnerIntakeSourceReadServiceTest.java | 7 +- .../publication/RealmPolicySourceTest.java | 7 +- .../SelectedOwnerIntakeSourceExportTest.java | 19 +- 20 files changed, 462 insertions(+), 216 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 c49af2fead..8ebafed7cd 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 @@ -18,7 +18,7 @@ Qualification remains partial. R21's focused gate freshly passes all 12 Game Des Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite. -R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in that invocation. R22 independently executes all 25 Game Design cross-service cases with zero failures, errors or skips and passes the previously missing Game Design static checks, formatting and documentation gates. Its only build failure is a nullable generic SQL extraction in the Game Session V1013 foreign-key test helper; a typed read preserves the exact trigger assertions, with its affected static recheck pending. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining Game Session static checks pass apart from that single helper finding; full-native qualification remains held. +R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in that invocation. R22 independently executes all 25 Game Design cross-service cases with zero failures, errors or skips and passes the previously missing Game Design static checks, formatting and documentation gates. Its only build failure is a nullable generic SQL extraction in the Game Session V1013 foreign-key test helper; a typed read preserves the exact trigger assertions, and R23 passes its affected Checkstyle, SpotBugs, formatting and documentation gates in 43 seconds on the published draft [#3246](https://github.com/benhook1013/FireMUD/pull/3246). Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining Game Session static checks pass after that correction; full-native qualification remains held. The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. R22 passively captures all ten exact run-owned PostgreSQL lifecycles with no ownership gaps or observer errors; its passing cross-service run does not reproduce the refusal. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 32045a4e20..463dc84ec9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation +The first required Source-stage R24 gate fails compilation in the new Account reservation and Game Design disclosure fixtures; it does not execute native or cross-service tasks. It freshly passes 1,455 Account unit cases with four existing skips and 746 Common unit cases with zero skips, plus Common static checks and documentation gates. The fixture corrections use typed Account assertion results, the existing isolated source-visibility test API, and the actual optional asset/gameplay snapshot model; no production capability or absent-family fallback is added. An unnecessary Account constructor suppression is removed. Their consolidated qualification remains pending, and no PostgreSQL readiness repair is claimed. + The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. ### Original StartSession protected activation source diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index ca79fda409..dfeed62594 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -366,10 +366,13 @@ public void requireSelectedOwnerIntakeAdmission( List sources, DraftCommitBinding selected) { requirePublicationAdmission(sources); Objects.requireNonNull(selected, "selected Draft binding is required"); - Record originalRow = dsl.fetchOne( - "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE", - selected.requestId(), selected.commitId()); - if (originalRow == null) throw new IllegalStateException("Selected author operation is unavailable"); + Record originalRow = + dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE", + selected.requestId(), + selected.commitId()); + if (originalRow == null) + throw new IllegalStateException("Selected author operation is unavailable"); DraftAuthorizationFenceBinding original = originalBinding(originalRow); if (!Arrays.equals(original.gameDesignBinding(), selected.canonicalBytes()) || !Ordering.COMMIT_ORDER.name().equals(originalRow.get("ordering", String.class)) @@ -382,10 +385,11 @@ public void requireSelectedOwnerIntakeAdmission( private void requireNoPendingSelectedOwnerIntakeSourceRead(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( - "SELECT source.operation_id FROM account_selected_owner_intake_source_read_sources source " - + "WHERE source.source_key = ? " - + "AND account_selected_owner_intake_source_read_is_pending(source.operation_id)", - source.key()).isEmpty()) { + "SELECT source.operation_id FROM account_selected_owner_intake_source_read_sources source " + + "WHERE source.source_key = ? " + + "AND account_selected_owner_intake_source_read_is_pending(source.operation_id)", + source.key()) + .isEmpty()) { throw new IllegalStateException("Selected owner intake source read remains pending"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java index 87f49ba243..da3fc6945c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.accountservice.service.session; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import java.util.Objects; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; @@ -22,10 +21,6 @@ public final class AccountSelectedOwnerIntakeSourceReadService { private final TransactionTemplate transaction; private final String namespace; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "Injected owner repository is intentionally shared and never exposed to callers") public AccountSelectedOwnerIntakeSourceReadService( AccountSelectedOwnerIntakeSourceReservationRepository repository, AccountControlUiCoordination registry, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index 3fd2c4dd1d..9ec88f73b5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -4,8 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import java.util.Map; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import org.flywaydb.core.Flyway; @@ -30,23 +30,32 @@ void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWit migration(source, schema, "1006").migrate(); assertVersionApplied(jdbc, schema, "1006"); - for (String version : List.of("137", "159", "160.1", "1000", "1001", "1002", "1003", "1004", "1004.1", "1004.2", "1004.3", "1005")) { + for (String version : + List.of( + "137", "159", "160.1", "1000", "1001", "1002", "1003", "1004", "1004.1", "1004.2", + "1004.3", "1005")) { assertVersionApplied(jdbc, schema, version); } assertVersionNotApplied(jdbc, schema, "1007"); - var ownerDsl = org.jooq.impl.DSL.using( - new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy(source), - org.jooq.SQLDialect.POSTGRES); - var ownerTransaction = new org.springframework.transaction.support.TransactionTemplate( - new org.springframework.jdbc.datasource.DataSourceTransactionManager(source)); - ownerTransaction.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + var ownerDsl = + org.jooq.impl.DSL.using( + new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy(source), + org.jooq.SQLDialect.POSTGRES); + var ownerTransaction = + new org.springframework.transaction.support.TransactionTemplate( + new org.springframework.jdbc.datasource.DataSourceTransactionManager(source)); + ownerTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); var account = new net.firedevops.firemud.accountservice.entity.Account(); account.setUsername("retained-parent-" + UUID.randomUUID()); account.setEmail(UUID.randomUUID() + "@example.test"); account.setPasswordHash("TEST_ONLY unused password verifier"); account.setRole("player"); - var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(ownerDsl); - assertThat(ownerTransaction.execute(status -> accounts.save(account))).isNotNull(); + var accounts = + new net.firedevops.firemud.accountservice.repository.AccountRepository(ownerDsl); + net.firedevops.firemud.accountservice.entity.Account savedAccount = + ownerTransaction.execute(status -> accounts.save(account)); + assertThat(savedAccount).isNotNull(); seedRetainedCombinedParentRows(jdbc); var retainedParent = retainedParentRows(jdbc); assertThat(retainedParent.values()).allSatisfy(rows -> assertThat(rows).isNotEmpty()); @@ -55,13 +64,21 @@ void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWit + "FROM flyway_schema_history h WHERE version IS NULL OR version <> '1007' " + "ORDER BY installed_rank"; var retainedHistory = jdbc.queryForList(historyQuery, String.class); - var protectionsGuard = functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])"); - var disposalGuard = functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()"); - var disposalWriterGuard = functionDefinition(jdbc, "account_initial_gameplay_login_writer_guard()"); - var alignmentGuard = functionDefinition(jdbc, "account_ss_activation_settlement_insert_guard()"); - assertThat(alignmentGuard).contains( - "terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); - assertThat(protectionsGuard).contains("account_start_session_admission_protections", "account_start_session_activation_protections"); + var protectionsGuard = + functionDefinition(jdbc, "account_ss_admission_assert_no_pending(text[])"); + var disposalGuard = + functionDefinition(jdbc, "account_initial_gameplay_login_disposal_immutable()"); + var disposalWriterGuard = + functionDefinition(jdbc, "account_initial_gameplay_login_writer_guard()"); + var alignmentGuard = + functionDefinition(jdbc, "account_ss_activation_settlement_insert_guard()"); + assertThat(alignmentGuard) + .contains( + "terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); + assertThat(protectionsGuard) + .contains( + "account_start_session_admission_protections", + "account_start_session_activation_protections"); assertWorldSourceExclusionGuards( functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"), functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"), @@ -128,27 +145,47 @@ private static Flyway migration( } private static void seedRetainedCombinedParentRows(JdbcTemplate jdbc) { - Long sagaId = jdbc.queryForObject( - "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", - Long.class, "retained-selected-source-upgrade", "PENDING"); + Long sagaId = + jdbc.queryForObject( + "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", + Long.class, + "retained-selected-source-upgrade", + "PENDING"); jdbc.update( "INSERT INTO saga_step(instance_id, name, status, attempt) VALUES (?, ?, ?, ?)", - sagaId, "retained-step", "PENDING", 3); + sagaId, + "retained-step", + "PENDING", + 3); jdbc.update( "INSERT INTO account_initial_gameplay_login_disposals(request_id, disposal_operation_id, " + "caller_workload, caller_context_id, disposal_digest, witness_canonical_bytes) " + "VALUES (?, ?, ?, ?, ?, ?)", - UUID.randomUUID(), UUID.randomUUID(), - "spiffe://firemud/ns/test/sa/game-session-service", UUID.randomUUID(), - "a".repeat(64), "retained parent disposal witness".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + "a".repeat(64), + "retained parent disposal witness".getBytes(java.nio.charset.StandardCharsets.UTF_8)); } /** Exact parent Account/source, disposal and Saga rows; no credential authority implied. */ private static Map> retainedParentRows(JdbcTemplate jdbc) { Map> rows = new java.util.LinkedHashMap<>(); - for (String table : List.of("accounts", "account_authority_source_records", "account_initial_gameplay_login_disposals", "saga_instance", "saga_step")) { - rows.put(table, jdbc.queryForList("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " - + table + " t ORDER BY to_jsonb(t)::TEXT", String.class)); + for (String table : + List.of( + "accounts", + "account_authority_source_records", + "account_initial_gameplay_login_disposals", + "saga_instance", + "saga_step")) { + rows.put( + table, + jdbc.queryForList( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + + " t ORDER BY to_jsonb(t)::TEXT", + String.class)); } return rows; } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 1d189ebf74..bd7304f0c0 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -134,7 +134,10 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { - if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget)) { + if (migrationTarget != null + && !"160.1".equals(migrationTarget) + && !"1006".equals(migrationTarget) + && !"1007".equals(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent or 1007 source-disclosure frontier is supported"); } @@ -550,9 +553,10 @@ private org.flywaydb.core.api.configuration.FluentConfiguration migrationConfigu .placeholders(Map.of("serviceSchema", migrationSchema)) .locations( "filesystem:" + accountMigrations(), - "filesystem:" + accountMigrations() - .resolve("../../../../../../common-saga/src/main/resources/db/migration/saga") - .normalize()); + "filesystem:" + + accountMigrations() + .resolve("../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()); } private static Path accountMigrations() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 4ae118be72..7610d66f8e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -28,11 +28,11 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** Lifecycle proof with real file watchers and a mocked channel factory, not a TLS handshake. */ class SelectedOwnerIntakeClientLifecycleTest { @@ -43,8 +43,7 @@ class SelectedOwnerIntakeClientLifecycleTest { @Timeout(15) @ResourceLock(Resources.SYSTEM_PROPERTIES) void closeReleasesClientMonitorBeforeDrainingCertificateCallback( - ClientKind kind, @TempDir Path directory) - throws Exception { + ClientKind kind, @TempDir Path directory) throws Exception { String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); System.setProperty(TLS_RELOAD_PROPERTY, "true"); CountDownLatch releaseClientMonitor = new CountDownLatch(1); @@ -168,7 +167,8 @@ private interface Initialize { void run() throws Exception; } - private record ClientHandle(AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} + private record ClientHandle( + AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} private enum ClientKind { SOURCE_READ, @@ -179,8 +179,6 @@ ClientHandle create( CommonGrpcClientProperties tls, GrpcChannelFactory factory) { return switch (this) { - - case SOURCE_READ -> { var client = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); @@ -190,7 +188,6 @@ ClientHandle create( var client = new GrpcSelectedOwnerIntakeSourceClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } - }; } } 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 3e99a47944..7f298ddd07 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 @@ -358,8 +358,7 @@ public Optional readCapture(GameDesignPublicationOperation operation) { && policy.isEmpty() && asset.isEmpty() && brand.isEmpty() - && templateConfig.isEmpty()) - return Optional.empty(); + && templateConfig.isEmpty()) return Optional.empty(); if (historical) { new GameDesignReviewedBaseRepository(dsl) .requireRetained(operation.account().input().selection().selectedCommit()); @@ -399,8 +398,7 @@ public Optional readSynchronized(TargetProof target, UUID c throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } boolean brandGenesisRetained = branding.readGenesis(target).isPresent(); - if (brand.isEmpty() - && (brandGenesisRetained || !BrandingSource.mutations(binding).isEmpty())) { + if (brand.isEmpty() && (brandGenesisRetained || !BrandingSource.mutations(binding).isEmpty())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } if (rules.isEmpty() @@ -417,8 +415,8 @@ public Optional readSynchronized(TargetProof target, UUID c } /** - * Read and export the exact synchronized source retained for an original selected Draft. - * Missing or partial owner history remains unavailable; it is never interpreted as empty. + * Read and export the exact synchronized source retained for an original selected Draft. Missing + * or partial owner history remains unavailable; it is never interpreted as empty. */ public SelectedOwnerIntakeSourceExport requireSelectedOwnerIntakeSource( SelectedOwnerIntakeSourceReadScope scope) { @@ -480,12 +478,7 @@ private static void requireCompleteScopes( boolean hasBranding, boolean hasGameplay, boolean hasTemplateConfig) { - if (!hasCommand - && !hasPolicy - && !hasAsset - && !hasBranding - && !hasGameplay - && !hasTemplateConfig + if (!hasCommand && !hasPolicy && !hasAsset && !hasBranding && !hasGameplay && !hasTemplateConfig || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -507,8 +500,7 @@ private static void requireCompleteScopes( && "effective".equals(unit.scopeId())) .toList(); List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); - List branding = - units.stream().filter(BrandingSourceRepository::isScope).toList(); + List branding = units.stream().filter(BrandingSourceRepository::isScope).toList(); var rules = units.stream().filter(GameplayRuleSource::isScope).toList(); var templateConfigs = units.stream().filter(TemplateConfigSource::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) @@ -598,13 +590,7 @@ public Genesis( Optional assetEvidence, Optional gameplayEvidence, Optional templateConfig) { - this( - policy, - command, - assetEvidence, - gameplayEvidence, - Optional.empty(), - templateConfig); + this(policy, command, assetEvidence, gameplayEvidence, Optional.empty(), templateConfig); } public Genesis( @@ -623,13 +609,7 @@ public Genesis( } public Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { - this( - policy, - command, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty()); + this(policy, command, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); } public AssetSnapshot.Genesis asset() { @@ -667,8 +647,7 @@ public record Application( || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || gameplay.isPresent() && !binding.equals(gameplay.orElseThrow().binding()) || branding.isPresent() && !binding.equals(branding.orElseThrow().binding()) - || templateConfig.isPresent() - && !binding.equals(templateConfig.orElseThrow().binding()) + || templateConfig.isPresent() && !binding.equals(templateConfig.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -752,8 +731,7 @@ public record SynchronizedSources( if (templateConfig.isPresent() && !command.binding().equals(templateConfig.orElseThrow().binding())) throw new IllegalStateException("TEMPLATE_CONFIG_SOURCE_SNAPSHOT_BINDING_CONFLICT"); - if (branding.isPresent() - && !command.binding().equals(branding.orElseThrow().binding())) + if (branding.isPresent() && !command.binding().equals(branding.orElseThrow().binding())) throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_BINDING_CONFLICT"); if (!command.binding().equals(policy.binding()) || assetEvidence.isPresent() @@ -766,13 +744,7 @@ public SynchronizedSources( CommandSnapshot command, RealmPolicySnapshot policy, Optional assetEvidence) { - this( - command, - policy, - assetEvidence, - Optional.empty(), - Optional.empty(), - Optional.empty()); + this(command, policy, assetEvidence, Optional.empty(), Optional.empty(), Optional.empty()); } public SynchronizedSources( @@ -780,13 +752,7 @@ public SynchronizedSources( RealmPolicySnapshot policy, Optional assetEvidence, Optional gameplayEvidence) { - this( - command, - policy, - assetEvidence, - gameplayEvidence, - Optional.empty(), - Optional.empty()); + this(command, policy, assetEvidence, gameplayEvidence, Optional.empty(), Optional.empty()); } public SynchronizedSources( @@ -795,13 +761,7 @@ public SynchronizedSources( Optional assetEvidence, Optional gameplayEvidence, Optional templateConfig) { - this( - command, - policy, - assetEvidence, - gameplayEvidence, - Optional.empty(), - templateConfig); + this(command, policy, assetEvidence, gameplayEvidence, Optional.empty(), templateConfig); } public AssetSnapshot asset() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java index 0ff938d33e..0b19e328b6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java @@ -42,8 +42,11 @@ public static SelectedOwnerIntakeSourceExport create( requireSelected(selected, sources.command().binding(), "COMMAND"); requireSelected(selected, sources.policy().binding(), "REALM_POLICY"); requireSelected(selected, sources.asset().binding(), "ASSET"); - var gameplay = sources.gameplayEvidence().orElseThrow( - () -> new IllegalStateException("Selected gameplay-rule source is incomplete")); + var gameplay = + sources + .gameplayEvidence() + .orElseThrow( + () -> new IllegalStateException("Selected gameplay-rule source is incomplete")); requireSelected(selected, gameplay.binding(), "GAMEPLAY_RULE"); var branding = sources 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 62de9f39ed..723b6d8ac8 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 @@ -9,9 +9,9 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; -import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index 2a0d902762..4cfd2cc057 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; 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.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; @@ -62,126 +63,317 @@ /** * Actual Account V1007 preliminary permission and independent GD six-family disclosure owners. - * Creator, environment, PKI, selected author admission/readbacks and authored inputs are controlled; - * no final intake authorization, recipient retention, genuine provenance or registration is proved. + * Creator, environment, PKI, selected author admission/readbacks and authored inputs are + * controlled; no final intake authorization, recipient retention, genuine provenance or + * registration is proved. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class SelectedOwnerSourceDisclosurePostgresIntegrationTest { private static final String NAMESPACE = "firemud"; private static final Network NETWORK = Network.newNetwork(); - @Container static final PostgreSQLContainer GDS = new PostgreSQLContainer<>(TestContainerImages.postgres()); - @Container static final PostgreSQLContainer ACCOUNT = new PostgreSQLContainer<>(TestContainerImages.postgres()); - @Container static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()) - .withNetwork(NETWORK).withNetworkAliases("selected-disclosure-primary") - .withExposedPorts(6379) - .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always"); - @Container static final GenericContainer REPLICA = new GenericContainer<>(TestContainerImages.redis()) - .withNetwork(NETWORK).dependsOn(REDIS) - .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always", "--replicaof", "selected-disclosure-primary", "6379"); + + @Container + static final PostgreSQLContainer GDS = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ACCOUNT = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("selected-disclosure-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "selected-disclosure-primary", + "6379"); + @TempDir Path temporary; @Test - void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefuses() throws Exception { + void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefuses() + throws Exception { var local = sourceStore(); - try (var fixture = new AccountControlUiOriginalOrderFixture( - ACCOUNT.getJdbcUrl(), ACCOUNT.getUsername(), ACCOUNT.getPassword(), REDIS.getHost(), - REDIS.getMappedPort(6379), temporary.resolve("account"), local.binding().target().canonicalTenantId(), - Clock.systemUTC(), "1007")) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + ACCOUNT.getJdbcUrl(), + ACCOUNT.getUsername(), + ACCOUNT.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + local.binding().target().canonicalTenantId(), + Clock.systemUTC(), + "1007")) { var issued = fixture.preparedOriginalCreator(); var f = issued.sources(); - assertThat(f.dsl.fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version IN ('1008','1009','1010')").get(0, Integer.class)).isZero(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version IN ('1008','1009','1010')") + .get(0, Integer.class)) + .isZero(); retainControlledSelectedAuthorAdmission(issued, local.binding()); - var reservations = new AccountSelectedOwnerIntakeSourceReservationService( - issued.actors(), f.fences, new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), f.manager, NAMESPACE); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), + f.fences, + new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), + f.manager, + NAMESPACE); var pki = new GenuineWorldSourceProofPki(temporary.resolve("pki")); var endpoints = new ServiceEndpointsProperties(); Server accountServer = null; Server sourceServer = null; try { - accountServer = server(pki, "account-service", new AccountSelectedOwnerIntakeSourceReadGrpcService( - fixture.selectedOwnerIntakeSourceReadService(NAMESPACE), NAMESPACE)); + accountServer = + server( + pki, + "account-service", + new AccountSelectedOwnerIntakeSourceReadGrpcService( + fixture.selectedOwnerIntakeSourceReadService(NAMESPACE), NAMESPACE)); endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); - try (var permissions = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, - pki.client("game-design-service"), new GrpcChannelFactory(), NAMESPACE)) { + try (var permissions = + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, + pki.client("game-design-service"), + new GrpcChannelFactory(), + NAMESPACE)) { permissions.init(); var permissionCalls = new AtomicInteger(); - var sourceOwner = new GameDesignSelectedOwnerIntakeSourceReadService( - new GameDesignSourceRepository(local.dsl()), local.manager(), request -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - permissionCalls.incrementAndGet(); - return permissions.read(request); - }, NAMESPACE); - sourceServer = server(pki, "game-design-service", new GameDesignSelectedOwnerIntakeSourceGrpcService(sourceOwner, NAMESPACE)); + var sourceOwner = + new GameDesignSelectedOwnerIntakeSourceReadService( + new GameDesignSourceRepository(local.dsl()), + local.manager(), + request -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()) + .isFalse(); + permissionCalls.incrementAndGet(); + return permissions.read(request); + }, + NAMESPACE); + sourceServer = + server( + pki, + "game-design-service", + new GameDesignSelectedOwnerIntakeSourceGrpcService(sourceOwner, NAMESPACE)); endpoints.setGameDesignService("127.0.0.1:" + sourceServer.getPort()); - try (var sources = new GrpcSelectedOwnerIntakeSourceClient(endpoints, - pki.client("account-service"), new GrpcChannelFactory(), NAMESPACE); - var wrongCaller = new GrpcSelectedOwnerIntakeSourceClient(endpoints, - pki.client("game-design-service"), new GrpcChannelFactory(), NAMESPACE)) { + try (var sources = + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, + pki.client("account-service"), + new GrpcChannelFactory(), + NAMESPACE); + var wrongCaller = + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, + pki.client("game-design-service"), + new GrpcChannelFactory(), + NAMESPACE)) { sources.init(); wrongCaller.init(); for (var owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { UUID requestId = UUID.randomUUID(); - var scope = asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment())); + var scope = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment())); var retained = retainedReservation(f, scope); var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); var content = sources.read(request); - var expected = local.tx().execute(ignored -> new GameDesignSourceRepository(local.dsl()).requireSelectedOwnerIntakeSource(scope)); + var expected = + local + .tx() + .execute( + ignored -> + new GameDesignSourceRepository(local.dsl()) + .requireSelectedOwnerIntakeSource(scope)); assertThat(content.canonicalBytes()).isEqualTo(expected.canonicalBytes()); assertThat(content.digest()).isEqualTo(expected.digest()); - for (String family : List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) - assertThat(content.snapshotBytes(family)).isNotEmpty(); - assertThat(sources.read(SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope)).canonicalBytes()).isEqualTo(content.canonicalBytes()); - assertThat(asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment())).canonicalBytes()).isEqualTo(scope.canonicalBytes()); + for (String family : + List.of( + "COMMAND", + "REALM_POLICY", + "ASSET", + "GAMEPLAY_RULE", + "BRANDING", + "TEMPLATE_CONFIG")) assertThat(content.snapshotBytes(family)).isNotEmpty(); + assertThat( + sources + .read( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope)) + .canonicalBytes()) + .isEqualTo(content.canonicalBytes()); + assertThat( + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment())) + .canonicalBytes()) + .isEqualTo(scope.canonicalBytes()); assertThat(retainedReservation(f, scope)).isEqualTo(retained); int beforeWrongPeer = permissionCalls.get(); - assertThatThrownBy(() -> wrongCaller.read(request)).isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> wrongCaller.read(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(permissionCalls).hasValue(beforeWrongPeer); - var substituted = new SelectedOwnerIntakeSourceReadScope(owner, NAMESPACE, UUID.randomUUID(), scope.fenceId(), scope.intakeRequestId(), scope.actorAccountId(), scope.selected()); - assertThatThrownBy(() -> sources.read(SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, substituted))).isInstanceOf(io.grpc.StatusRuntimeException.class); + var substituted = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.randomUUID(), + scope.fenceId(), + scope.intakeRequestId(), + scope.actorAccountId(), + scope.selected()); + assertThatThrownBy( + () -> + sources.read( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, substituted))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(retainedReservation(f, scope)).isEqualTo(retained); - assertThat(asGameDesign(() -> reservations.abortSourceRead(scope)).state().name()).isEqualTo("ABORTED"); + assertThat(asGameDesign(() -> reservations.abortSourceRead(scope)).state().name()) + .isEqualTo("ABORTED"); var aborted = retainedReservation(f, scope); - assertThatThrownBy(() -> sources.read(request)).isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy(() -> asGameDesign(() -> reservations.reserveSourceRead(issued.compact(), requestId, owner, local.binding(), issued.environment()))).isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> sources.read(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); asGameDesign(() -> reservations.abortSourceRead(scope)); assertThat(retainedReservation(f, scope)).isEqualTo(aborted); - assertThat(local.tx().execute(ignored -> new GameDesignSourceRepository(local.dsl()).requireSelectedOwnerIntakeSource(scope)).canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat( + local + .tx() + .execute( + ignored -> + new GameDesignSourceRepository(local.dsl()) + .requireSelectedOwnerIntakeSource(scope)) + .canonicalBytes()) + .isEqualTo(content.canonicalBytes()); } } } } finally { - for (var server : new Server[] {sourceServer, accountServer}) if (server != null) server.shutdownNow(); - for (var server : new Server[] {sourceServer, accountServer}) if (server != null) assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + for (var server : new Server[] {sourceServer, accountServer}) + if (server != null) server.shutdownNow(); + for (var server : new Server[] {sourceServer, accountServer}) + if (server != null) assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } } } - private static String retainedReservation(AccountControlUiOwnerSourcesFixture f, SelectedOwnerIntakeSourceReadScope scope) { - return f.dsl.fetchSingle("SELECT row_to_json(r)::TEXT || ':' || xmin::TEXT FROM account_selected_owner_intake_source_read_reservations r WHERE operation_id = ?", scope.operationId()).get(0, String.class); + private static String retainedReservation( + AccountControlUiOwnerSourcesFixture f, SelectedOwnerIntakeSourceReadScope scope) { + return f.dsl + .fetchSingle( + "SELECT row_to_json(r)::TEXT || ':' || xmin::TEXT FROM account_selected_owner_intake_source_read_reservations r WHERE operation_id = ?", + scope.operationId()) + .get(0, String.class); } /** Controlled upstream terminal readbacks; the preliminary permission itself is never mocked. */ - private static void retainControlledSelectedAuthorAdmission(AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { + private static void retainControlledSelectedAuthorAdmission( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { var f = issued.sources(); var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); - var original = new DraftAuthorizationFenceBinding(UUID.randomUUID(), selected.requestId(), selected.commitId(), UUID.randomUUID(), f.account.getAccountUuid(), f.tenant, selected.target().canonicalVersionId(), selected.baseCommitId(), "0", selected.canonicalBytes(), selected.canonicalBytes(), selected.digest(), captured.sources()).withRequiredOwners(); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); - f.tx(() -> { - for (var owner : original.requiredOwners()) f.fences.recordOwnerReadback(original, - new DraftAuthorizationFenceBinding.OwnerReadback(owner, DraftAuthorizationFenceBinding.Outcome.COMMITTED, original.operationId(), original.commitId(), original.fenceId(), original.inputDigest(), original.canonicalBytes(), new byte[] {1})); - return null; - }); + f.tx( + () -> { + for (var owner : original.requiredOwners()) + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); } private static Local sourceStore() { String schema = "selected_disclosure_" + UUID.randomUUID().toString().replace("-", ""); var data = new DriverManagerDataSource(GDS.getJdbcUrl(), GDS.getUsername(), GDS.getPassword()); data.setSchema(schema); - Flyway.configure().dataSource(data).schemas(schema).defaultSchema(schema) - .table("flyway_schema_history_game_design_service").placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration").load().migrate(); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var manager = new DataSourceTransactionManager(data); var tx = new TransactionTemplate(manager); @@ -196,36 +388,78 @@ private static Local sourceStore() { version.setVersionState(VersionLifecycleState.DRAFT); version.setVersionStateEpoch(1L); var saved = tx.execute(ignored -> new VersionRepository(dsl).save(version)); - var target = new DraftCommitBinding.TargetProof(saved.getCanonicalTenantId(), saved.getCanonicalVersionId(), saved.getId(), saved.getTenantId(), saved.getIdentitySourceGameRowId(), saved.getIdentitySourceGameTenantKey(), saved.getIdentitySourceProvenanceKind()); - var binding = DraftCommitBinding.create(target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", - List.of(new DraftCommitBinding.RevisionPayload("0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, - CommandSource.upsertPayload("{\"schemaVersion\":1,\"commandId\":\"DISCLOSURE\",\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true,\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"))), - List.of(new DraftCommitBinding.AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE, CommandSource.SCOPE, target.canonicalVersionId().toString(), CommandSource.SCOPE, "effective", "0"))); - tx.executeWithoutResult(ignored -> { - var source = new GameDesignSourceRepository(dsl); - var reviewed = new GameDesignReviewedBaseRepository(dsl).resolve(target, DraftBaseReference.parse(binding.baseCommitId())); - source.claimReviewed(binding, reviewed); - var coordinator = new DraftCommitCoordinatorRepository(dsl); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = source.apply(binding); - coordinator.advanceSourceVisibilityFence(binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(applied.ownerOutcome()))); - source.captureSynchronized(binding); - coordinator.releaseApplicationSlot(binding); - }); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"DISCLOSURE\",\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true,\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + target.canonicalVersionId().toString(), + CommandSource.SCOPE, + "effective", + "0"))); + tx.executeWithoutResult( + ignored -> { + var source = new GameDesignSourceRepository(dsl); + var reviewed = + new GameDesignReviewedBaseRepository(dsl) + .resolve(target, DraftBaseReference.parse(binding.baseCommitId())); + source.claimReviewed(binding, reviewed); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = source.apply(binding); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + dsl, binding, List.of(applied.ownerOutcome())); + source.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); return new Local(dsl, manager, tx, binding); } - private static Server server(GenuineWorldSourceProofPki pki, String service, io.grpc.BindableService handler) throws Exception { + private static Server server( + GenuineWorldSourceProofPki pki, String service, io.grpc.BindableService handler) + throws Exception { var identity = pki.server(service); return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext(GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()).trustManager(pki.ca().toFile()).clientAuth(ClientAuth.REQUIRE).build()) - .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())).build().start(); + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) + .build() + .start(); } private static T asGameDesign(Supplier action) { - var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service").orElseThrow()); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); var previous = context.attach(); try { return action.get(); @@ -234,5 +468,9 @@ private static T asGameDesign(Supplier action) { } } - private record Local(DSLContext dsl, DataSourceTransactionManager manager, TransactionTemplate tx, DraftCommitBinding binding) {} + private record Local( + DSLContext dsl, + DataSourceTransactionManager manager, + TransactionTemplate tx, + DraftCommitBinding binding) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index 25674b7d74..5d4648e4ac 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -95,7 +95,7 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH .containsEntry("THEME", "EMPTY"); assertThat( synchronizedSources - .gameplay() + .gameplayEvidence().orElseThrow() .manifest() .families() .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) @@ -145,8 +145,7 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH @Test void retainedVersionCannotAcquireMissingBrandingGenesis() { var f = fixture("58"); - var original = - binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); + var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); f.tx.executeWithoutResult( ignored -> { var coordinator = new DraftCommitCoordinatorRepository(f.dsl); @@ -224,7 +223,7 @@ void retainedVersionCannotAcquireMissingBrandingGenesis() { historical.command().canonicalJson(), historical.policy().canonicalJson(), historical.asset().canonicalJson(), - historical.gameplay().canonicalJson())) + historical.gameplayEvidence().orElseThrow().canonicalJson())) .isEqualTo(sourceJson); assertThat( f.dsl 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 dbea9e423f..e967ff0168 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 @@ -22,10 +22,10 @@ import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; 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 717f8af68e..ddceffa259 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 @@ -18,10 +18,10 @@ 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.CommandSource; 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyApplication; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index 9a1d97347c..3e6ec183a8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -21,6 +21,7 @@ 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.common.gamedesign.CommandSource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; @@ -29,7 +30,6 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; -import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; 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 index d09291b4e8..21ee6fc447 100644 --- 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 @@ -8,8 +8,8 @@ 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.AssetSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.gamedesign.publication.AssetSnapshot; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; import org.junit.jupiter.api.Test; 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 5bdc3eb0c6..7f14f21f1d 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 @@ -13,10 +13,10 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; 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.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java index 6d079a3010..b4b81de7f1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java @@ -239,7 +239,12 @@ private static GameDesignSourceRepository.SynchronizedSources sources( var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); return new GameDesignSourceRepository.SynchronizedSources( - command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + command, + policy, + Optional.of(asset), + Optional.of(gameplay), + Optional.of(branding), + Optional.of(template)); } private static SelectedOwnerIntakeSourceReadScope scope( 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 index 8b6ce635ef..ecf180cf61 100644 --- 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 @@ -28,13 +28,10 @@ void policyClassifierRecognizesKnownSiblingOwnersAndRejectsUnknownKinds() { "2", UUID.randomUUID(), AssetSource.upsertPayload("41", "map", AssetSource.Requiredness.REQUIRED)); - var template = - policyRevision("3", UUID.randomUUID(), TemplateConfigSource.deletePayload("7")); + var template = policyRevision("3", UUID.randomUUID(), TemplateConfigSource.deletePayload("7")); var branding = policyRevision( - "4", - UUID.randomUUID(), - "{\"revisionKind\":\"" + BrandingSource.REVISION_KIND + "\"}"); + "4", UUID.randomUUID(), "{\"revisionKind\":\"" + BrandingSource.REVISION_KIND + "\"}"); var unknown = policyRevision("5", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); assertThat(RealmPolicySource.isPolicyRevision(policy)).isTrue(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java index 4fe0d656c0..dcc88b4f94 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -43,7 +43,7 @@ void framesTheScopeAndAllSixFamiliesInFixedOrder() { frameFamily(expected, "COMMAND", sources.command().canonicalBytes()); frameFamily(expected, "REALM_POLICY", sources.policy().canonicalBytes()); frameFamily(expected, "ASSET", sources.asset().canonicalBytes()); - frameFamily(expected, "GAMEPLAY_RULE", sources.gameplay().canonicalBytes()); + frameFamily(expected, "GAMEPLAY_RULE", sources.gameplayEvidence().orElseThrow().canonicalBytes()); frameFamily(expected, "BRANDING", sources.branding().orElseThrow().canonicalBytes()); frameFamily( expected, "TEMPLATE_CONFIG", sources.templateConfig().orElseThrow().canonicalBytes()); @@ -75,7 +75,7 @@ void sharedConsumerDecodesExactCompleteExportsForBothOwners() { .isEqualTo(sources.policy().canonicalBytes()); assertThat(content.snapshotBytes("ASSET")).isEqualTo(sources.asset().canonicalBytes()); assertThat(content.snapshotBytes("GAMEPLAY_RULE")) - .isEqualTo(sources.gameplay().canonicalBytes()); + .isEqualTo(sources.gameplayEvidence().orElseThrow().canonicalBytes()); assertThat(content.snapshotBytes("BRANDING")) .isEqualTo(sources.branding().orElseThrow().canonicalBytes()); assertThat(content.snapshotBytes("TEMPLATE_CONFIG")) @@ -134,16 +134,16 @@ void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { new GameDesignSourceRepository.SynchronizedSources( complete.command(), complete.policy(), - complete.asset(), - complete.gameplay(), + complete.assetEvidence(), + complete.gameplayEvidence(), Optional.empty(), complete.templateConfig()); var missingTemplate = new GameDesignSourceRepository.SynchronizedSources( complete.command(), complete.policy(), - complete.asset(), - complete.gameplay(), + complete.assetEvidence(), + complete.gameplayEvidence(), complete.branding(), Optional.empty()); @@ -183,7 +183,12 @@ static GameDesignSourceRepository.SynchronizedSources sources( var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); return new GameDesignSourceRepository.SynchronizedSources( - command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + command, + policy, + Optional.of(asset), + Optional.of(gameplay), + Optional.of(branding), + Optional.of(template)); } static SelectedOwnerIntakeSourceReadScope scope(Owner owner, DraftCommitBinding selected) { From 86f03ed1bff550082a8ec318d691725540410131 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:25:14 +1300 Subject: [PATCH 07/36] test: qualify selected source fixtures against actual owner history --- .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 2 +- ...sionProtectionPostgresIntegrationTest.java | 7 +- ...rceReservationPostgresIntegrationTest.java | 2 +- ...urceDisclosurePostgresIntegrationTest.java | 4 +- ...BrandingSourcePostgresIntegrationTest.java | 281 ++++++++++++++---- ...meDesignSourcePostgresIntegrationTest.java | 20 +- .../SelectedOwnerIntakeSourceExportTest.java | 3 +- 9 files changed, 243 insertions(+), 82 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index ad042220a1..91d7a153ca 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Prepared PostgreSQL upgrade and disclosure compositions have not run. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. +The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Their first native invocation fails in fixture setup; corrected upgrade and disclosure proof remains pending. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 034fd1f4d2..4152de8640 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -340,3 +340,7 @@ Entry format: - `2026-10-15`: Classes-only foreign-owner proof artifacts intentionally omit application and Flyway resources. A composed test that reads another owner’s migrations from disk must declare those directories as task inputs; otherwise a SQL-only change can leave the composition up-to-date. The selected Game Logic proof exposed this after its forward migration was reconciled, and Game Design now tracks the foreign Game Logic and World migration directories. - `2026-10-15`: Allocate forward migrations against the actual resolved Flyway history, including shared Saga resources and later service-owned migrations. The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history. The receiving Account parent already reaches V1005, while Saga reaches V1002. Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. + +- `2026-10-16`: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. A Document source gate automatically acquired the lock before its delayed peer completion message arrived; busy admission remains unrun proof. + +- `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 463dc84ec9..cc47c28e34 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation -The first required Source-stage R24 gate fails compilation in the new Account reservation and Game Design disclosure fixtures; it does not execute native or cross-service tasks. It freshly passes 1,455 Account unit cases with four existing skips and 746 Common unit cases with zero skips, plus Common static checks and documentation gates. The fixture corrections use typed Account assertion results, the existing isolated source-visibility test API, and the actual optional asset/gameplay snapshot model; no production capability or absent-family fallback is added. An unnecessary Account constructor suppression is removed. Their consolidated qualification remains pending, and no PostgreSQL readiness repair is claimed. +The corrected Source-stage R26 gate freshly passes 1,455 Account units with four existing skips and 635 Game Design units with zero skips; Common's 746 units retain R24 attribution. All affected static, formatting and documentation checks pass. Native qualification remains held: Account executes 291 cases with three failures, Game Design executes 162 with five failures, and Game Design cross-service executes 26 with two failures, all with zero skips. Eight failures expose fixture setup or frontier drift; the other two are a PostgreSQL host-port refusal in an inherited composition and a Redis host-port startup timeout. The prepared corrections use actual Branding genesis and reviewed bases, retained V1025 five-family history without Branding backfill, the Game Design-owned migration directory, the current Account source-exclusion guards and a bounded fixture username. Their affected native recheck remains pending. No production authority, absent-family fallback, schema or readiness-policy change is introduced. The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index fbfedc3a4c..83e548e6dc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -498,10 +498,9 @@ void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { assertThat(definition) .contains( "account_ss_admission_assert_no_pending", - "account_start_session_world_participations") - // The actual published parent has the canonical World guard. Selected-owner source - // reservations remain a separate V130 receiving obligation, outside passive V165. - .doesNotContain("account_selected_owner_intake_source_read"); + "account_start_session_world_participations", + "account_selected_owner_intake_source_read_is_pending", + "account_selected_owner_intake_source_read_reservations"); } String hold = fixture diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index 9ec88f73b5..f3d463cbf6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -47,7 +47,7 @@ void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWit ownerTransaction.setIsolationLevel( org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); var account = new net.firedevops.firemud.accountservice.entity.Account(); - account.setUsername("retained-parent-" + UUID.randomUUID()); + account.setUsername("selected-" + UUID.randomUUID()); account.setEmail(UUID.randomUUID() + "@example.test"); account.setPasswordHash("TEST_ONLY unused password verifier"); account.setRole("player"); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index 4cfd2cc057..95ac0d1aae 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -371,7 +371,9 @@ private static Local sourceStore() { .defaultSchema(schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index 5d4648e4ac..65eaf8afd6 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftBaseReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.gamedesign.BrandingSource; @@ -52,20 +53,7 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH var f = fixture(null); var logo = asset(f, "logo.png"); var ordinary = asset(f, "ordinary.png"); - // Borrow only typed policy input; the fixture is not Account publication authorization. - var policy = - net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures.fresh( - f.target) - .account() - .input() - .selection() - .selectedCommit() - .revisions() - .stream() - .map(DraftCommitBinding.RevisionPayload::payload) - .filter(p -> p.contains("REALM_ENTRY_POLICY")) - .findFirst() - .orElseThrow(); + var policy = policyPayload(); var first = binding( f, @@ -95,7 +83,8 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH .containsEntry("THEME", "EMPTY"); assertThat( synchronizedSources - .gameplayEvidence().orElseThrow() + .gameplayEvidence() + .orElseThrow() .manifest() .families() .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) @@ -143,18 +132,31 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH } @Test - void retainedVersionCannotAcquireMissingBrandingGenesis() { - var f = fixture("58"); + void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesis() { + var f = fixture("1025"); var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); f.tx.executeWithoutResult( ignored -> { var coordinator = new DraftCommitCoordinatorRepository(f.dsl); coordinator.claim(original); + var policyGenesis = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow(); + var commands = + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); + var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); + byte[] reviewedEvidence = + historicalReviewedGenesisBytes(f.target, policyGenesis, commandGenesis); + insertReviewedBaseV1( + f.dsl, + original, + reviewedEvidence, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + reviewedEvidence)); coordinator.claimApplicationSlot(original); coordinator.markOwnerInProgress( original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var commands = - new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); var applied = commands.apply(original).orElseThrow(); var out = new java.io.ByteArrayOutputStream(); net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( @@ -183,62 +185,124 @@ void retainedVersionCannotAcquireMissingBrandingGenesis() { .captureSynchronized(original); new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) .captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository(f.dsl) + .captureSynchronized(original); coordinator.releaseApplicationSlot(original); }); - var originalBytes = - f.dsl - .fetchSingle( - "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get(0, byte[].class); var originalSources = - List.of("command_source", "realm_policy", "asset_source", "gameplay_rule"); - var sourceJson = + List.of( + "command_source", + "realm_policy", + "asset_source", + "gameplay_rule", + "template_config_source"); + var originalSourceRows = originalSources.stream() .map( name -> f.dsl .fetchSingle( - "SELECT snapshot_json FROM game_design_" + "SELECT snapshot_json, xmin::text AS row_xmin FROM game_design_" + name + "_snapshot WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get(0, String.class)) + f.target.canonicalVersionId())) .toList(); - var fenceJson = + var sourceJson = + originalSourceRows.stream().map(row -> row.get("snapshot_json", String.class)).toList(); + var sourceXmins = + originalSourceRows.stream().map(row -> row.get("row_xmin", String.class)).toList(); + var originalFence = + f.dsl.fetchSingle( + "SELECT to_jsonb(f)::text AS row_json, xmin::text AS row_xmin " + + "FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()); + var originalResult = + f.dsl.fetchSingle( + "SELECT result_bytes, xmin::text AS row_xmin " + + "FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()); + var originalCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest, xmin::text AS row_xmin " + + "FROM game_design_draft_commit WHERE canonical_version_id = ? AND commit_id = ?", + f.target.canonicalVersionId(), + original.commitId()); + var v1025MigrationHistory = f.dsl - .fetchSingle( - "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get(0, String.class); + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success AS history_entry " + + "FROM flyway_schema_history_game_design_service " + + "WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues("history_entry", String.class); + f.migrate(); + assertThat( + f.dsl + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success AS history_entry " + + "FROM flyway_schema_history_game_design_service " + + "WHERE version IS NOT NULL ORDER BY installed_rank LIMIT ?", + v1025MigrationHistory.size()) + .getValues("history_entry", String.class)) + .containsExactlyElementsOf(v1025MigrationHistory); var historical = new GameDesignSourceRepository(f.dsl) .readSynchronized(f.target, original.commitId()) .orElseThrow(); assertThat(historical.branding()).isEmpty(); assertThat(historical.command().binding()).isEqualTo(original); + assertThat(historical.templateConfig()).isPresent(); assertThat( List.of( historical.command().canonicalJson(), historical.policy().canonicalJson(), historical.asset().canonicalJson(), - historical.gameplayEvidence().orElseThrow().canonicalJson())) + historical.gameplayEvidence().orElseThrow().canonicalJson(), + historical.templateConfig().orElseThrow().canonicalJson())) .isEqualTo(sourceJson); assertThat( - f.dsl - .fetchSingle( - "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get(0, String.class)) - .isEqualTo(fenceJson); - assertThat( - f.dsl - .fetchSingle( - "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get(0, byte[].class)) - .isEqualTo(originalBytes); + originalSources.stream() + .map( + name -> + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get("row_xmin", String.class)) + .toList()) + .isEqualTo(sourceXmins); + var migratedFence = + f.dsl.fetchSingle( + "SELECT to_jsonb(f)::text AS row_json, xmin::text AS row_xmin " + + "FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()); + assertThat(migratedFence.get("row_json", String.class)) + .isEqualTo(originalFence.get("row_json", String.class)); + assertThat(migratedFence.get("row_xmin", String.class)) + .isEqualTo(originalFence.get("row_xmin", String.class)); + var migratedResult = + f.dsl.fetchSingle( + "SELECT result_bytes, xmin::text AS row_xmin " + + "FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()); + assertThat(migratedResult.get("result_bytes", byte[].class)) + .isEqualTo(originalResult.get("result_bytes", byte[].class)); + assertThat(migratedResult.get("row_xmin", String.class)) + .isEqualTo(originalResult.get("row_xmin", String.class)); + var migratedCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest, xmin::text AS row_xmin " + + "FROM game_design_draft_commit WHERE canonical_version_id = ? AND commit_id = ?", + f.target.canonicalVersionId(), + original.commitId()); + assertThat(migratedCommit.get("binding_json", String.class)) + .isEqualTo(originalCommit.get("binding_json", String.class)); + assertThat(migratedCommit.get("input_digest", String.class)) + .isEqualTo(originalCommit.get("input_digest", String.class)); + assertThat(migratedCommit.get("row_xmin", String.class)) + .isEqualTo(originalCommit.get("row_xmin", String.class)); assertThatThrownBy( () -> f.tx.execute( @@ -252,6 +316,12 @@ void retainedVersionCannotAcquireMissingBrandingGenesis() { ignored -> new BrandingSourceRepository(f.dsl).enrollFreshDraft(f.target))) .isInstanceOf(IllegalStateException.class) .hasMessage("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); + assertThatThrownBy( + () -> + f.tx.execute( + ignored -> new BrandingSourceRepository(f.dsl).captureSynchronized(original))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BRANDING_SOURCE_GENESIS_UNAVAILABLE"); assertThatThrownBy(() -> new GameDesignSourceRepository(f.dsl).readGenesis(f.target)) .isInstanceOf(IllegalStateException.class) .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); @@ -288,15 +358,82 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { .isEmpty(); } + private static byte[] historicalReviewedGenesisBytes( + DraftCommitBinding.TargetProof target, + net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis policyGenesis, + CommandSource.NewDraftGenesisReceipt commandGenesis) { + var ownerEvidence = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + ownerEvidence, "shared-policy-command-genesis/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + ownerEvidence, policyGenesis.creationTransactionId()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + ownerEvidence, policyGenesis.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + ownerEvidence, commandGenesis.canonicalBytes()); + + var evidence = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, DraftBaseReference.SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, DraftBaseReference.Kind.GENESIS.name()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, "genesis:" + policyGenesis.receiptId()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, target.canonicalTenantId().toString()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, target.canonicalVersionId().toString()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, Long.toString(target.gameDesignVersionRowId())); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, target.gameDesignVersionTenantKey()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, Long.toString(target.sourceGameRowId())); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, target.sourceGameTenantKey()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, target.sourceProvenanceKind()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + evidence, ownerEvidence.toByteArray()); + return evidence.toByteArray(); + } + + private static void insertReviewedBaseV1( + DSLContext dsl, DraftCommitBinding binding, byte[] evidenceBytes, String evidenceDigest) { + var reference = DraftBaseReference.parse(binding.baseCommitId()); + 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.HISTORICAL_SCHEMA, + evidenceBytes, + evidenceDigest); + } + private void apply(Fixture f, DraftCommitBinding binding) { f.tx.executeWithoutResult( ignored -> { + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, + new GameDesignReviewedBaseRepository(f.dsl) + .resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - coordinator.claim(binding); coordinator.claimApplicationSlot(binding); coordinator.markOwnerInProgress( binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var sources = new GameDesignSourceRepository(f.dsl); var applied = sources.apply(binding); coordinator.advanceSourceVisibilityFence( binding, @@ -351,7 +488,40 @@ private DraftCommitBinding binding( scope.equals(primaryScope) ? epoch : "0")) .toList(); return DraftCommitBinding.create( - f.target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", revisions, units); + f.target, + UUID.randomUUID(), + UUID.randomUUID(), + currentBaseReference(f), + revisions, + units); + } + + private static String currentBaseReference(Fixture f) { + UUID visibleCommit = + f.dsl + .fetchSingle( + "SELECT visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId()) + .get("visible_commit_id", UUID.class); + if (visibleCommit != null) return visibleCommit.toString(); + UUID genesisReceipt = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow() + .receiptId(); + return "genesis:" + genesisReceipt; + } + + private static String policyPayload() { + return "{\"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\"}}"; } private GameAsset asset(Fixture f, String name) { @@ -398,8 +568,8 @@ private Fixture fixture(String maximumMigration) { tx.execute( ignored -> { if (maximumMigration == null) return new VersionRepository(dsl).save(version); - // Retained fixture intentionally uses the pre-branding producer, in its actual - // insert transaction. + // Retained fixture uses the V1025 producer transaction, with every then-current + // source genesis except Branding deliberately enrolled. long id = dsl.fetchSingle( "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, version_number, version_state, version_state_epoch, is_script_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', 1, 'DRAFT', 1, FALSE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING id", @@ -432,6 +602,9 @@ private Fixture fixture(String maximumMigration) { new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( dsl) .enrollFreshDraft(oldTarget); + new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository( + dsl) + .enrollFreshDraft(oldTarget); return retained; })); var target = 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 e967ff0168..3cc7e645be 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 @@ -78,7 +78,7 @@ void firstReferenceRejectsStaleBrandingMetadataUpdate() throws Exception { private static void assertFirstReferenceRejectsStaleUpdate(boolean branding, boolean metadata) throws Exception { - Fixture fixture = fixture(branding); + Fixture fixture = fixture(); byte[] bytes = {0, 1, (byte) 0xff}; long assetId = fixture @@ -958,10 +958,6 @@ private static String command(String id, String alias) { } private static Fixture fixture() { - return fixture(false); - } - - private static Fixture fixture(boolean branding) { String schema = "gd_combined_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource( @@ -996,20 +992,6 @@ private static Fixture fixture(boolean branding) { version.setTenantId(game.getTenantId()); version.setVersionNumber(1); version = new VersionRepository(dsl).save(version); - if (branding) { - dsl.execute( - "INSERT INTO game_design_branding_source_genesis " - + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json, roles_json) " - + "SELECT canonical_tenant_id, canonical_version_id, version_id, ?, creation_transaction_id, target_json, " - + "'{\"RESOURCE\":\"EMPTY\",\"LOGO\":\"EMPTY\",\"FAVICON\":\"EMPTY\",\"THEME\":\"EMPTY\"}' " - + "FROM game_design_asset_source_genesis WHERE version_id = ?", - UUID.randomUUID(), - version.getId()); - dsl.execute( - "INSERT INTO game_design_branding_source_head (canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) " - + "SELECT canonical_tenant_id, canonical_version_id, '0', receipt_id FROM game_design_branding_source_genesis WHERE version_id = ?", - version.getId()); - } return new TargetProof( version.getCanonicalTenantId(), version.getCanonicalVersionId(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java index dcc88b4f94..10d1290ec1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -43,7 +43,8 @@ void framesTheScopeAndAllSixFamiliesInFixedOrder() { frameFamily(expected, "COMMAND", sources.command().canonicalBytes()); frameFamily(expected, "REALM_POLICY", sources.policy().canonicalBytes()); frameFamily(expected, "ASSET", sources.asset().canonicalBytes()); - frameFamily(expected, "GAMEPLAY_RULE", sources.gameplayEvidence().orElseThrow().canonicalBytes()); + frameFamily( + expected, "GAMEPLAY_RULE", sources.gameplayEvidence().orElseThrow().canonicalBytes()); frameFamily(expected, "BRANDING", sources.branding().orElseThrow().canonicalBytes()); frameFamily( expected, "TEMPLATE_CONFIG", sources.templateConfig().orElseThrow().canonicalBytes()); From 3d20a861a79e2a6580cfe1f05aca7930d2bc12a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:36:17 +1300 Subject: [PATCH 08/36] Use actual reviewed genesis in retained source fixtures --- ...urceDisclosurePostgresIntegrationTest.java | 9 +- ...BrandingSourcePostgresIntegrationTest.java | 109 +++++++----------- 2 files changed, 47 insertions(+), 71 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index 95ac0d1aae..cc954a7b9d 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -372,8 +372,7 @@ private static Local sourceStore() { .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) .locations( - "filesystem:" - + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); @@ -399,12 +398,16 @@ private static Local sourceStore() { saved.getIdentitySourceGameRowId(), saved.getIdentitySourceGameTenantKey(), saved.getIdentitySourceProvenanceKind()); + var policyGenesis = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(dsl) + .readGenesis(target) + .orElseThrow(); var binding = DraftCommitBinding.create( target, UUID.randomUUID(), UUID.randomUUID(), - "base-commit-0", + "genesis:" + policyGenesis.receiptId(), List.of( new DraftCommitBinding.RevisionPayload( "0", diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index 65eaf8afd6..b02f88c558 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -8,6 +8,7 @@ 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.DraftBaseReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -146,14 +147,27 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi var commands = new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); - byte[] reviewedEvidence = - historicalReviewedGenesisBytes(f.target, policyGenesis, commandGenesis); - insertReviewedBaseV1( - f.dsl, - original, - reviewedEvidence, - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( - reviewedEvidence)); + var assetGenesis = + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow(); + var gameplayGenesis = + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow(); + var templateGenesis = + new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow(); + var reviewedEvidence = + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis( + policyGenesis, + commandGenesis, + Optional.of(assetGenesis), + Optional.of(gameplayGenesis), + Optional.of(templateGenesis))); + insertReviewedBaseV2(f.dsl, original, reviewedEvidence); coordinator.claimApplicationSlot(original); coordinator.markOwnerInProgress( original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); @@ -200,12 +214,11 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi originalSources.stream() .map( name -> - f.dsl - .fetchSingle( - "SELECT snapshot_json, xmin::text AS row_xmin FROM game_design_" - + name - + "_snapshot WHERE canonical_version_id = ?", - f.target.canonicalVersionId())) + f.dsl.fetchSingle( + "SELECT snapshot_json, xmin::text AS row_xmin FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId())) .toList(); var sourceJson = originalSourceRows.stream().map(row -> row.get("snapshot_json", String.class)).toList(); @@ -358,51 +371,16 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { .isEmpty(); } - private static byte[] historicalReviewedGenesisBytes( - DraftCommitBinding.TargetProof target, - net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis policyGenesis, - CommandSource.NewDraftGenesisReceipt commandGenesis) { - var ownerEvidence = new java.io.ByteArrayOutputStream(); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - ownerEvidence, "shared-policy-command-genesis/v1"); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - ownerEvidence, policyGenesis.creationTransactionId()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - ownerEvidence, policyGenesis.canonicalBytes()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - ownerEvidence, commandGenesis.canonicalBytes()); - - var evidence = new java.io.ByteArrayOutputStream(); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, DraftBaseReference.SCHEMA); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, DraftBaseReference.Kind.GENESIS.name()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, "genesis:" + policyGenesis.receiptId()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, target.canonicalTenantId().toString()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, target.canonicalVersionId().toString()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, Long.toString(target.gameDesignVersionRowId())); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, target.gameDesignVersionTenantKey()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, Long.toString(target.sourceGameRowId())); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, target.sourceGameTenantKey()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, target.sourceProvenanceKind()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - evidence, ownerEvidence.toByteArray()); - return evidence.toByteArray(); - } - - private static void insertReviewedBaseV1( - DSLContext dsl, DraftCommitBinding binding, byte[] evidenceBytes, String evidenceDigest) { - var reference = DraftBaseReference.parse(binding.baseCommitId()); + private static void insertReviewedBaseV2( + DSLContext dsl, + DraftCommitBinding binding, + GameDesignReviewedBaseEvidence reviewedEvidence) { + if (!binding.target().equals(reviewedEvidence.target()) + || !binding.baseCommitId().equals(reviewedEvidence.reference().canonicalValue())) { + throw new IllegalArgumentException( + "Reviewed genesis evidence must match the exact historical Draft base"); + } + var reference = reviewedEvidence.reference(); dsl.execute( "INSERT INTO game_design_reviewed_draft_base " + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest, " @@ -417,9 +395,9 @@ private static void insertReviewedBaseV1( reference.kind().name(), reference.identity(), reference.canonicalValue(), - GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA, - evidenceBytes, - evidenceDigest); + GameDesignReviewedBaseEvidence.SCHEMA, + reviewedEvidence.canonicalBytes(), + reviewedEvidence.digest()); } private void apply(Fixture f, DraftCommitBinding binding) { @@ -488,12 +466,7 @@ private DraftCommitBinding binding( scope.equals(primaryScope) ? epoch : "0")) .toList(); return DraftCommitBinding.create( - f.target, - UUID.randomUUID(), - UUID.randomUUID(), - currentBaseReference(f), - revisions, - units); + f.target, UUID.randomUUID(), UUID.randomUUID(), currentBaseReference(f), revisions, units); } private static String currentBaseReference(Fixture f) { From c06f111f234f97b74b0aa61052f7d82d6f788eae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:38:37 +1300 Subject: [PATCH 09/36] Record passing selected source owner proof and infrastructure limits --- .../microservices/account-service/runtime-and-data.md | 2 +- .../implementation-tracking/player-access-and-session.md | 4 ++-- .../draft/BrandingSourcePostgresIntegrationTest.java | 7 +++---- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 91d7a153ca..ae1ab11fee 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Their first native invocation fails in fixture setup; corrected upgrade and disclosure proof remains pending. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. +The selected-recipient source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Focused PostgreSQL upgrade and source-disclosure proof passes; full-native qualification remains held on inherited PostgreSQL/Redis failures. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index cc47c28e34..8797b31496 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,9 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation -The corrected Source-stage R26 gate freshly passes 1,455 Account units with four existing skips and 635 Game Design units with zero skips; Common's 746 units retain R24 attribution. All affected static, formatting and documentation checks pass. Native qualification remains held: Account executes 291 cases with three failures, Game Design executes 162 with five failures, and Game Design cross-service executes 26 with two failures, all with zero skips. Eight failures expose fixture setup or frontier drift; the other two are a PostgreSQL host-port refusal in an inherited composition and a Redis host-port startup timeout. The prepared corrections use actual Branding genesis and reviewed bases, retained V1025 five-family history without Branding backfill, the Game Design-owned migration directory, the current Account source-exclusion guards and a bounded fixture username. Their affected native recheck remains pending. No production authority, absent-family fallback, schema or readiness-policy change is introduced. +The corrected Source-stage R26 gate freshly passes 1,455 Account units with four existing skips and 635 Game Design units with zero skips; Common's 746 units retain R24 attribution. All affected static, formatting and documentation checks pass. R28 freshly passes all eight affected PostgreSQL cases with zero skips: Account V1007 upgrade and current source-exclusion guards, three Branding source and retained-history cases, two stale-Branding first-reference races, and the actual Account-permission-to-Game-Design disclosure composition. The retained V1025 proof uses actual five-family genesis and asset-bound v2 reviewed evidence, preserves historical bytes and row metadata, and acquires no Branding lineage through upgrade. Full-native qualification remains held: R26 Account executes 291 cases with three failures, Game Design 162 with five failures, and Game Design cross-service 26 with two failures, all with zero skips. Eight fixture failures are corrected by the focused proof; the inherited PostgreSQL host-port refusal and Redis host-port startup timeout remain unresolved. No production authority, absent-family fallback, schema or readiness-policy change is introduced. -The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, but has not run. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition is being prepared; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. +The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, and passes in R28. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition passes with controlled upstream inputs; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. ### Original StartSession protected activation source diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index b02f88c558..c78b1291bb 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -156,7 +156,8 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi .readGenesis(f.target) .orElseThrow(); var templateGenesis = - new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository(f.dsl) + new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository( + f.dsl) .readGenesis(f.target) .orElseThrow(); var reviewedEvidence = @@ -372,9 +373,7 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { } private static void insertReviewedBaseV2( - DSLContext dsl, - DraftCommitBinding binding, - GameDesignReviewedBaseEvidence reviewedEvidence) { + DSLContext dsl, DraftCommitBinding binding, GameDesignReviewedBaseEvidence reviewedEvidence) { if (!binding.target().equals(reviewedEvidence.target()) || !binding.baseCommitId().equals(reviewedEvidence.reference().canonicalValue())) { throw new IllegalArgumentException( From bf8bda7d553e9eece53002d38c9973c07f10e8cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:49:01 +1300 Subject: [PATCH 10/36] Keep source writers blocked by selected owner reservations --- .../DraftAuthorizationFenceRepository.java | 12 ++++++++-- ...urceDisclosurePostgresIntegrationTest.java | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index dfeed62594..96fa1d078a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -383,6 +383,12 @@ public void requireSelectedOwnerIntakeAdmission( } private void requireNoPendingSelectedOwnerIntakeSourceRead(List sources) { + if (hasPendingSelectedOwnerIntakeSourceRead(sources)) { + throw new IllegalStateException("Selected owner intake source read remains pending"); + } + } + + private boolean hasPendingSelectedOwnerIntakeSourceRead(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( "SELECT source.operation_id FROM account_selected_owner_intake_source_read_sources source " @@ -390,9 +396,10 @@ private void requireNoPendingSelectedOwnerIntakeSourceRead(List + "AND account_selected_owner_intake_source_read_is_pending(source.operation_id)", source.key()) .isEmpty()) { - throw new IllegalStateException("Selected owner intake source read remains pending"); + return true; } } + return false; } private boolean hasPendingGameLogicIntake(List sources) { @@ -890,7 +897,8 @@ private List affectedOperations(List sources) { private boolean allAffectedSettled(List sources) { if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources) - || hasPendingWorldParticipation(sources)) { + || hasPendingWorldParticipation(sources) + || hasPendingSelectedOwnerIntakeSourceRead(sources)) { return false; } for (UUID operation : affectedOperations(sources)) { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index cc954a7b9d..bf2e85e78c 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -273,8 +273,30 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu NAMESPACE, substituted))) .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(retainedReservation(f, scope)).isEqualTo(retained); + var capturedSources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var blockedWriter = + new net.firedevops.firemud.accountservice.authordraft + .DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), capturedSources.sources(), new byte[] {7}); + assertThat(f.tx(() -> f.fences.requestSourceChange(blockedWriter))) + .isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(blockedWriter))) + .isFalse(); + assertThat(f.tx(() -> f.fences.sourceAbortPermitted(blockedWriter))) + .isFalse(); assertThat(asGameDesign(() -> reservations.abortSourceRead(scope)).state().name()) .isEqualTo("ABORTED"); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(blockedWriter))) + .isTrue(); + f.tx( + () -> { + f.fences.markSourceAborted( + blockedWriter, + net.firedevops.firemud.accountservice.authordraft + .DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); var aborted = retainedReservation(f, scope); assertThatThrownBy(() -> sources.read(request)) .isInstanceOf(io.grpc.StatusRuntimeException.class); From 4fba63641b1c3abef355199dd2c747b9bc2e3947 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:59:20 +1300 Subject: [PATCH 11/36] Format strengthened preliminary source writer proof --- ...SelectedOwnerSourceDisclosurePostgresIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index bf2e85e78c..248b1df7cb 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -277,7 +277,7 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); var blockedWriter = new net.firedevops.firemud.accountservice.authordraft - .DraftAuthorizationFenceRepository.SourceChange( + .DraftAuthorizationFenceRepository.SourceChange( UUID.randomUUID(), capturedSources.sources(), new byte[] {7}); assertThat(f.tx(() -> f.fences.requestSourceChange(blockedWriter))) .isFalse(); @@ -294,7 +294,8 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu f.fences.markSourceAborted( blockedWriter, net.firedevops.firemud.accountservice.authordraft - .DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + .DraftAuthorizationFenceRepository.SourceChangeAbortReason + .DEFINITIVE_ABORT); return null; }); var aborted = retainedReservation(f, scope); From bf991d3d72b3ad215675c1fb3bad7db02fc9f8d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:07:01 +1300 Subject: [PATCH 12/36] Make selected-source fixture flags visible across threads --- .../SelectedOwnerIntakeSourceReadClientMtlsTest.java | 4 ++-- .../gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java index 3ce2d53d90..91d329820b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java @@ -55,8 +55,8 @@ class SelectedOwnerIntakeSourceReadClientMtlsTest { private static TestPki pki; private final AtomicInteger calls = new AtomicInteger(); private Server server; - private boolean stall; - private boolean substitute; + private volatile boolean stall; + private volatile boolean substitute; @BeforeAll static void certificates() throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java index a525c43a3f..5687995444 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java @@ -77,9 +77,9 @@ class SelectedOwnerIntakeSourceClientMtlsTest { private final AtomicInteger calls = new AtomicInteger(); private final AtomicInteger responseBytes = new AtomicInteger(); private Server server; - private boolean stall; - private boolean substituteEcho; - private boolean largeResponse; + private volatile boolean stall; + private volatile boolean substituteEcho; + private volatile boolean largeResponse; @BeforeAll static void certificates() throws Exception { From 1dd916119954bd1628cb5e0cd5ce0d0c6718dd19 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:27:21 +1300 Subject: [PATCH 13/36] Release original client monitors before draining certificate watchers --- .../player-access-and-session.md | 6 + ...sionRedeemedOperationProjectionClient.java | 8 +- ...orldParticipationHistoricalReadClient.java | 8 +- ...ActivationProtectionAcquisitionClient.java | 8 +- ...nActivationProtectionSettlementClient.java | 8 +- ...ionWorldParticipationSettlementClient.java | 8 +- .../WorldAuthoredVersionIdentityClient.java | 8 +- .../AuthoredWorldVersionStateClient.java | 8 +- ...tartSessionLaunchDescriptorReadClient.java | 8 +- ...tSessionTemplateAssociationReadClient.java | 8 +- ...ginalStartSessionCurrentAttemptClient.java | 8 +- .../tenant/AuthoredWorldSourceClient.java | 8 +- .../WorldAuthoredSourceIntakeClient.java | 8 +- ...rtSessionActivationTerminalReadClient.java | 8 +- ...StartSessionProtectedActivationClient.java | 8 +- ...artSessionExecutionTerminalReadClient.java | 8 +- ...edCoreAndSpawnReadClientLifecycleTest.java | 112 +++++++++++++++++- 17 files changed, 189 insertions(+), 49 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d946900f13..57b4d320ec 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,12 @@ The standalone source prepares Account activation-protection acquisition, retain These components and their World consumer remain unregistered. The focused corrected gate passes in 2m55s with 13 Account PostgreSQL cases and four World/Account/Game Session compositions freshly executed without failures, errors or skips. The positive composition uses actual Account participation settlement, fresh operation-bound Game Session reads, Account currentness/source protection, guarded World ACTIVE and exact authenticated Account terminal settlement. The changed-attempt refusal preserves relevant row bytes and xmin. Forward Account V1006 aligns the incoming result digest with the existing World-owned prefixed contract while retaining every other guard predicate, installed history, pending protection and source bytes; bare and substituted digests refuse. The ten Game Session native association cases retain their passing focused gate, and preceding 1,419 Account units (four existing filesystem skips), 2,385 Game Session units and 619 Common units retain their original attribution. World’s 578 units freshly pass after the transport denial correction; its 88 ordinary native cases retain the preceding full gate. Static/format checks pass. Upstream creator/issuer/environment, Logging claims, GDS release/publication authority and PKI remain controlled; these results qualify owner mechanics and establish no genuine authority, registered runtime, admission, Entity placement or delivery. No generic Account permission, synthetic owner response or renewed lease is supplied. The [Account API owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Session continuation contract](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation), and [World tracker](./world-runtime-and-movement.md#original-startsession-protected-activation-source) own the relevant boundaries. +### Original source and StartSession client shutdown + +Fifteen explicit authored-source and StartSession clients now update their local closed/initialized state under the client monitor and release it before the shared certificate watcher drains reload callbacks. The existing [authored-core and spawn lifecycle fixture](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java) covers the additional Game Design, World, Account and Game Session dependencies, including the adjacent StartSession launch and template readers. Their request, owner and registration boundaries remain unchanged. + +At test-only source `eba3b0ab183a50ed1fdb31c930b3531fd5ddad1d`, real file-watch callbacks block on each client monitor and all fifteen added cases fail the shutdown monitor assertion; the four earlier cases pass. At corrected source `dc07a8b7f1c72c1f2dfdbb5af7825b51da7e9f5d`, all nineteen lifecycle cases and the affected client/base suites pass freshly: seventy-five cases across seventeen XML reports, with zero failures, errors or skips. Main and Test Checkstyle/SpotBugs pass; the formatter ran and the final formatting check is up to date. The lifecycle cases verify bounded close, closed-init refusal and exactly one shutdown per constructed mocked channel. They exercise real file-watch contention with controlled files, without a TLS handshake or owner SQL; other client suites retain their own controlled unit or socket boundaries. This correction does not complete a genuine Gameplay handoff or establish deployment authority. Seven Game Logic intake clients with the same source pattern remain outside this focused original-source/StartSession parcel. + ### Selected gameplay-rule intake authorization prerequisite The prepared Account source adds standalone Game Logic intake authorization, an immutable source-read reservation, exact finalized recovery, authorization reads, source reads and terminal settlement. It requires the same-namespace Game Design workload and current Account creator/environment evidence for fresh work. The actual selected Game Design source read precedes Account finalization; settlement independently reads the exact Game Logic terminal before Account SQL. Retained finalized recovery uses the original request and credential hash and never resumes a fresh source read. Common typed models, protobuf codecs and authenticated clients carry the complete immutable binding. The existing Account V95–V97 storage remains unchanged; these owners add no registration, route, enabling configuration or new SQL migration. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java index b8e1f33c0d..db12157d92 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java @@ -153,9 +153,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java index 568f7ca3b0..5b8ade5b73 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java @@ -117,9 +117,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java index ae50ffe8ae..fceeeb05df 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java @@ -110,9 +110,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java index 15efced355..dc3275a515 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java @@ -111,9 +111,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java index ad556bbbb2..3a48e43d8d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java @@ -113,9 +113,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java index 91329c39d8..cea108ebc5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java @@ -102,9 +102,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java index b39d740f2c..e7f5130795 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java @@ -97,9 +97,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java index d8ccef0248..73069d602f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java @@ -111,9 +111,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java index 8126646f72..1c57da1311 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java @@ -111,9 +111,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java index 528c648708..6e9b925a2c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java @@ -115,9 +115,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java index 2b70389f2e..293d04ae92 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java @@ -97,9 +97,11 @@ protected AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlock } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java index 28d0f5aa4f..6099fa1da9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -132,9 +132,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java index c542e60004..0a38fb68a2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java @@ -102,9 +102,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java index 6984086f2d..4f3e258372 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java @@ -105,9 +105,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java index 8023bac9c4..b309bdba0c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java @@ -110,9 +110,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java index 2c22d87c47..bfe1d361c0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java @@ -21,14 +21,26 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionSettlementClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionWorldParticipationSettlementClient; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionProtectedActivationClient; import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.ResourceLock; @@ -37,9 +49,10 @@ import org.junit.jupiter.params.provider.EnumSource; /** - * Real file-watcher lifecycle proof with mocked channels, not a TLS handshake. The controlled - * self-signed Entity certificate satisfies only the spawn client's local constructor URI check; key - * and CA files are readable placeholders, never production credentials. + * Real file-watcher lifecycle proof for authored-source, publication and StartSession clients with + * mocked channels, not a TLS handshake. The controlled self-signed Entity certificate satisfies + * only the spawn client's local constructor URI check; key and CA files are readable placeholders, + * never production credentials. */ class AuthoredCoreAndSpawnReadClientLifecycleTest { private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; @@ -180,7 +193,22 @@ private enum ClientKind { AUTHORED_CORE, SPAWN_REQUIREMENTS, WORLD_SELECTED_FREEZE, - WORLD_SELECTED_INVENTORY; + WORLD_SELECTED_INVENTORY, + STARTSESSIONREDEEMEDOPERATIONPROJECTION, + ACCOUNTSTARTSESSIONWORLDPARTICIPATIONHISTORICALREAD, + GRPCACCOUNTSTARTSESSIONACTIVATIONPROTECTIONACQUISITION, + GRPCACCOUNTSTARTSESSIONACTIVATIONPROTECTIONSETTLEMENT, + GRPCACCOUNTSTARTSESSIONWORLDPARTICIPATIONSETTLEMENT, + WORLDAUTHOREDVERSIONIDENTITY, + AUTHOREDWORLDVERSIONSTATE, + STARTSESSIONLAUNCHDESCRIPTORREAD, + STARTSESSIONTEMPLATEASSOCIATIONREAD, + GRPCORIGINALSTARTSESSIONCURRENTATTEMPT, + AUTHOREDWORLDSOURCE, + WORLDAUTHOREDSOURCEINTAKE, + GRPCWORLDORIGINALSTARTSESSIONACTIVATIONTERMINALREAD, + GRPCWORLDORIGINALSTARTSESSIONPROTECTEDACTIVATION, + WORLDSTARTSESSIONEXECUTIONTERMINALREAD; ClientHandle create( ServiceEndpointsProperties endpoints, @@ -205,6 +233,82 @@ ClientHandle create( new WorldSelectedPublicationArtifactInventoryClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case STARTSESSIONREDEEMEDOPERATIONPROJECTION -> { + var client = + new StartSessionRedeemedOperationProjectionClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNTSTARTSESSIONWORLDPARTICIPATIONHISTORICALREAD -> { + var client = + new AccountStartSessionWorldParticipationHistoricalReadClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCACCOUNTSTARTSESSIONACTIVATIONPROTECTIONACQUISITION -> { + var client = + new GrpcAccountStartSessionActivationProtectionAcquisitionClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCACCOUNTSTARTSESSIONACTIVATIONPROTECTIONSETTLEMENT -> { + var client = + new GrpcAccountStartSessionActivationProtectionSettlementClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCACCOUNTSTARTSESSIONWORLDPARTICIPATIONSETTLEMENT -> { + var client = + new GrpcAccountStartSessionWorldParticipationSettlementClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLDAUTHOREDVERSIONIDENTITY -> { + var client = new WorldAuthoredVersionIdentityClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case AUTHOREDWORLDVERSIONSTATE -> { + var client = new AuthoredWorldVersionStateClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case STARTSESSIONLAUNCHDESCRIPTORREAD -> { + var client = new StartSessionLaunchDescriptorReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case STARTSESSIONTEMPLATEASSOCIATIONREAD -> { + var client = + new StartSessionTemplateAssociationReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCORIGINALSTARTSESSIONCURRENTATTEMPT -> { + var client = + new GrpcOriginalStartSessionCurrentAttemptClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case AUTHOREDWORLDSOURCE -> { + var client = new AuthoredWorldSourceClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLDAUTHOREDSOURCEINTAKE -> { + var client = new WorldAuthoredSourceIntakeClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCWORLDORIGINALSTARTSESSIONACTIVATIONTERMINALREAD -> { + var client = + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GRPCWORLDORIGINALSTARTSESSIONPROTECTEDACTIVATION -> { + var client = + new GrpcWorldOriginalStartSessionProtectedActivationClient( + endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLDSTARTSESSIONEXECUTIONTERMINALREAD -> { + var client = + new WorldStartSessionExecutionTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } }; } } From 44c3fc0f730b3c7921493375849445d9f14e5a0c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:40:41 +1300 Subject: [PATCH 14/36] Restore independent original launch-read identity guard and focused proof --- design/project-management/ai-observations.md | 2 + .../player-access-and-session.md | 6 ++ ...nstanceLaunchAssociationReadGrpcCodec.java | 1 + ...RedeemedOperationProjectionClientTest.java | 31 +++++- ...nceLaunchAssociationReadGrpcCodecTest.java | 96 +++++++++++++++++++ 5 files changed, 132 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3a3fe31883..2bff8c956e 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -110,3 +110,5 @@ Entry format: - Observation: verifying nonoverlapping blobs and paragraphs unique against the merge base missed receiver status that also appeared in the base. Main later compared the complete receiver document, restored every original receiver paragraph byte-for-byte, and retained the incoming concise status and relocated proof. No production source changed. - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. + +- `2026-10-16`: Check both public mapping directions when an internal read requires an identity distinct from its original operation. The launch-association receiver retained that guard while a refactor removed it from the request encoder; the receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 57b4d320ec..eeaed091fd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,6 +24,12 @@ Fifteen explicit authored-source and StartSession clients now update their local At test-only source `eba3b0ab183a50ed1fdb31c930b3531fd5ddad1d`, real file-watch callbacks block on each client monitor and all fifteen added cases fail the shutdown monitor assertion; the four earlier cases pass. At corrected source `dc07a8b7f1c72c1f2dfdbb5af7825b51da7e9f5d`, all nineteen lifecycle cases and the affected client/base suites pass freshly: seventy-five cases across seventeen XML reports, with zero failures, errors or skips. Main and Test Checkstyle/SpotBugs pass; the formatter ran and the final formatting check is up to date. The lifecycle cases verify bounded close, closed-init refusal and exactly one shutdown per constructed mocked channel. They exercise real file-watch contention with controlled files, without a TLS handshake or owner SQL; other client suites retain their own controlled unit or socket boundaries. This correction does not complete a genuine Gameplay handoff or establish deployment authority. Seven Game Logic intake clients with the same source pattern remain outside this focused original-source/StartSession parcel. +### Original owner read bindings + +The [canonical launch-association request encoder](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java) now applies its existing independent-read-identity guard before encoding. The receiver already rejects reuse of the original control-plane identity. The current owning codec test also retains closed request/response fields, complete launch pairs and canonical realm/owner UUIDs. The existing [Account redeemed-projection socket fixture](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java) again uses a source fence independent of the issuance fence and rejects a changed complete original reference; [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read) owns that distinction. + +At test-only source `653c42cea1f7759d9c96e1ac3be64b8dfa026efb`, the receiver rejects the reused identity and the producer fails the expected-refusal assertion; nine other selected cases pass. Corrected source `cefbf09ebb8cdd9f4786f2cf878a5ec794dae151` passes all 917 Common cases across 198 fresh XML reports, with zero failures, errors or skips, plus affected Main/Test static analysis and formatting. This includes the four owning launch-codec cases, six controlled-PKI Account-projection loopback cases and nineteen inherited file-watcher lifecycle cases. The socket service supplies controlled Account responses and performs no owner SQL; the launch cases prove codec behavior. These results establish no genuine issuer, currentness, deployed composition or Gameplay handoff authority. + ### Selected gameplay-rule intake authorization prerequisite The prepared Account source adds standalone Game Logic intake authorization, an immutable source-read reservation, exact finalized recovery, authorization reads, source reads and terminal settlement. It requires the same-namespace Game Design workload and current Account creator/environment evidence for fresh work. The actual selected Game Design source read precedes Account finalization; settlement independently reads the exact Game Logic terminal before Account SQL. Retained finalized recovery uses the original request and credential hash and never resumes a fresh source read. Common typed models, protobuf codecs and authenticated clients carry the complete immutable binding. The existing Account V95–V97 storage remains unchanged; these owners add no registration, route, enabling configuration or new SQL migration. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java index bee50e0088..4fe397e94d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -128,6 +128,7 @@ private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request request) { Objects.requireNonNull(request, "request"); + requireIndependentReadIdentity(request); var builder = GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() .setReadRequestId(request.readRequestId().toString()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java index 76c4839df2..a5baa0d795 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java @@ -133,6 +133,9 @@ void exactSameNamespaceWorkloadsReadTheOriginalProjectionOverPhysicalMtls() thro .getBytes(StandardCharsets.UTF_8)); assertThat(response.getAuthorityEvidenceBundle().toByteArray()) .containsExactly(fixture.postTuple().authorityEvidenceBundleBytes()); + assertThat(response.getBundleReference().getSourceFence()).isEqualTo("17"); + assertThat(response.getBundleReference().getSourceFence()) + .isNotEqualTo(Long.toString(response.getIssuanceFence())); assertThat(applicationCalls).hasValue(1); assertThat(receivedPeer.get()) .isNotNull() @@ -177,6 +180,22 @@ void rejectsChangedOperationBindingAndUnknownResponseFields() throws Exception { .hasMessageContaining("invalid redeemed StartSession operation projection"); } + @Test + void rejectsChangedCompleteReferenceWhileSourceFenceIsIndependentOfIssuanceFence() + throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.CHANGED_SOURCE_FENCE); + client = newClient(server); + client.init(); + + assertThat(fixture.postTuple().bundleReference().sourceFence()) + .isNotEqualTo(Long.toString(ISSUANCE_FENCE)); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + } + @Test void rejectsExpiredAccountReferenceEvenWhenResponseEchoesOriginalBundle() throws Exception { Fixture fixture = fixture(CLOCK_NOW.minusSeconds(60L)); @@ -258,6 +277,12 @@ public void readRedeemedOperationProjection( ReadRedeemedOperationProjectionResponse response = response(fixture); if (mode == ResponseMode.CHANGED_DIGEST) { response = response.toBuilder().setMutationDigest("0".repeat(64)).build(); + } else if (mode == ResponseMode.CHANGED_SOURCE_FENCE) { + response = + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder().setSourceFence("18").build()) + .build(); } else if (mode == ResponseMode.UNKNOWN_FIELD) { response = response.toBuilder() @@ -359,10 +384,7 @@ private static Fixture fixture(Instant expiresAt, String targetNamespace) { "redeemed-projection-request-β", ACTOR_ID, action); StartSessionAuthorityEvidenceBundle.BundleReference reference = new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - Long.toString(ISSUANCE_FENCE), - "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "17", "18446744073709551615"); byte[] bundle = authorityEvidenceBundle(preTuple, expiresAt, targetNamespace); StartSessionPostAuthorizationExecutionTuple postTuple = StartSessionPostAuthorizationExecutionTuple.createHuman( @@ -458,6 +480,7 @@ private static Timestamp timestamp(Instant value) { private enum ResponseMode { EXACT, CHANGED_DIGEST, + CHANGED_SOURCE_FENCE, UNKNOWN_FIELD, BLOCK_UNTIL_RELEASED } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java index 1fe7731d5c..9e268df07c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.UnknownFieldSet; import java.time.Instant; +import java.util.Locale; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; @@ -68,11 +70,17 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( response.toBuilder().clearOwnerAttemptId().build(), response.toBuilder().setOwnerAttemptId("not-a-uuid").build(), response.toBuilder().setOwnerAttemptId("00000000-0000-0000-0000-000000000000").build(), + response.toBuilder() + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString().toUpperCase(Locale.ROOT)) + .build(), response.toBuilder().setOwnerFence(0).build(), response.toBuilder().setOwnerFence(-1).build(), response.toBuilder().clearCanonicalRealmId().build(), response.toBuilder().setCanonicalRealmId("not-a-uuid").build(), response.toBuilder().setCanonicalRealmId("00000000-0000-0000-0000-000000000000").build(), + response.toBuilder() + .setCanonicalRealmId(CANONICAL_REALM_ID.toString().toUpperCase(Locale.ROOT)) + .build(), response.toBuilder().clearCatalogRevision().build(), response.toBuilder().setCatalogRevision(0L).build(), response.toBuilder().setCatalogRevision(-1L).build() @@ -213,6 +221,94 @@ void accountOperationRoundTripsExactTupleAndOwnerSelectorAndRejectsPartialOrChan .isInstanceOf(IllegalArgumentException.class); } + @Test + void rejectsOriginalRequestIdentityAtBothLaunchReadWireBoundaries() throws Exception { + var binding = AuthoringFixtures.lifecycleEvidence("PREPARING", 1L).launchBinding(); + var request = request(binding); + var reusedIdentity = + new Request( + READ_REQUEST_ID, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + READ_REQUEST_ID.toString(), + request.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest()); + var reusedWire = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request).toBuilder() + .setControlPlaneRequestId(READ_REQUEST_ID.toString()) + .build(); + + assertThatThrownBy( + () -> CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest(reusedWire)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact canonical launch association request required") + .hasRootCauseMessage( + "Launch association read identity must remain separate from the original request"); + assertThatThrownBy( + () -> CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(reusedIdentity)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from the original request"); + } + + @Test + void rejectsChangedEchoMissingLaunchPairAndUnknownTopLevelOrNestedFields() throws Exception { + var binding = AuthoringFixtures.lifecycleEvidence("PREPARING", 1L).launchBinding(); + var request = request(binding); + var wire = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request); + var response = response(request, binding); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + for (var invalid : + java.util.List.of( + response.toBuilder().setControlPlaneRequestId("changed").build(), + response.toBuilder().clearLaunchDescriptor().build(), + response.toBuilder().clearReleaseAttestation().build(), + response.toBuilder().setUnknownFields(unknown).build(), + response.toBuilder() + .setLaunchDescriptor( + response.getLaunchDescriptor().toBuilder().setUnknownFields(unknown)) + .build(), + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder().setUnknownFields(unknown)) + .build())) { + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static Request request( + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + return new Request( + READ_REQUEST_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + binding.releaseAttestation().evidenceDigest()); + } + private static StartSessionPostAuthorizationExecutionTuple originalTuple( net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { var pre = From 03f7c0c2151f6073ead60988a48cd3a880111fba Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:39:10 +1300 Subject: [PATCH 15/36] test(common): restore complete synchronized visibility result proof --- ...ame-authoring-publishing-and-activation.md | 6 + ...aftSynchronizedVisibilityEvidenceTest.java | 143 ++++++++++++++++++ 2 files changed, 149 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 5453272433..1498d972a2 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 @@ -44,6 +44,12 @@ Component qualification passes. The final Game Design gate freshly executes all The caller also closes its required Game Design gameplay-rule source owner: fresh Draft enrollment retains an explicit empty inventory, coordinated writes preserve ordered rule revisions and exact owner results, and synchronized captures retain inherited rule provenance. The canonical rule grammar remains in the shared `GameplayRuleSource`; current V1005 storage guards remain intact. Focused SQL proof covers hidden staging and exact replay, stale epochs, inherited provenance with explicit deletion, and rollback. These controlled owner cases do not prove an immutable production-selected release. +### Synchronized Draft visibility proof + +The existing Common visibility-evidence test retains the complete World and Entity APPLIED result vector, verifies defensive World result bytes and refuses unknown owner status, a substituted affected scope, a non-synchronized workflow state or a changed full-input fence digest. The existing arbitrary-precision exact expected-plus-one counter case remains intact. + +The focused visibility and Draft-binding owner classes freshly pass ten cases with zero failures, errors or skips. Test Checkstyle and SpotBugs pass, canonical formatting passes and the final style checks are up to date. This is structural evidence over controlled result vectors; it does not execute a coordinator, SQL owner or authenticated transport, and it supplies no creator, issuer, currentness, publication, activation or genuine handoff authority. + ### Account terminal-settlement continuation The prepared continuation adds unregistered Account reconciliation and exact Game Design/World terminal-read adapters. Account reads missing required-owner evidence outside its transactions, rechecks the immutable original binding and ordering, retains exact readbacks through the existing repository, and derives settlement through that repository's complete-owner predicate. Unsupported required v2 participants stay pending. World preserves current APPLIED graph and inbound-closure decoding and uses the inherited definitive-abort owner history; Game Design reads its existing durable terminal owner. No migration, service registration, source authority, publication or runtime permission is added. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java index c4eae206bf..2d088881f1 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java @@ -6,8 +6,11 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.Base64; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -19,6 +22,7 @@ import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.Request; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; class DraftSynchronizedVisibilityEvidenceTest { private static final String EXPECTED_EPOCH = "900719925474099312345678901234567890"; @@ -54,6 +58,53 @@ void requiresExactlyOneAppliedEpochAdvanceAcrossLargeCounters() throws Exception } } + @Test + void completeAllOwnerFenceValidatesAndReturnsDefensiveExactWorldResult() { + var evidence = evidence(multiOwnerBinding(), resultVector(multiOwnerBinding())); + + evidence.requireValid(); + assertThat(evidence.appliedOwnerResults()).hasSize(2); + assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultIdentity()) + .isEqualTo("world-result"); + byte[] resultBytes = evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultBytes(); + resultBytes[0] = 0; + assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultBytes()) + .containsExactly("world-result-bytes".getBytes(StandardCharsets.UTF_8)); + } + + @Test + void rejectsIncompleteOrSubstitutedFenceAndOwnerResults() { + DraftCommitBinding binding = multiOwnerBinding(); + String vector = resultVector(binding); + + assertThatThrownBy(() -> evidence(binding, vector.replace("APPLIED", "UNKNOWN"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("terminal APPLIED"); + assertThatThrownBy(() -> evidence(binding, vector.replace("WORLD_TEMPLATE", "OTHER"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bound epoch declaration"); + assertThatThrownBy( + () -> + new DraftSynchronizedVisibilityEvidence( + request(), binding, "APPLYING", fence(binding, vector))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not bound"); + assertThatThrownBy( + () -> + new DraftSynchronizedVisibilityEvidence( + request(), + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + "sha256:" + "f".repeat(64), + vector, + OffsetDateTime.parse("2026-10-06T00:00:00Z")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("full input"); + } + private static DraftSynchronizedVisibilityEvidence evidence(String resultingEpoch) throws Exception { DraftCommitBinding binding = binding(); @@ -128,6 +179,98 @@ private static DraftCommitBinding binding() { EXPECTED_EPOCH))); } + private static DraftSynchronizedVisibilityEvidence evidence( + DraftCommitBinding binding, String vector) { + return new DraftSynchronizedVisibilityEvidence( + request(), binding, "SYNCHRONIZED", fence(binding, vector)); + } + + private static DraftSynchronizedVisibilityEvidence.Fence fence( + DraftCommitBinding binding, String vector) { + return new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + binding.digest(), + vector, + OffsetDateTime.parse("2026-10-06T00:00:00Z")); + } + + private static DraftSynchronizedVisibilityEvidence.Request request() { + return new DraftSynchronizedVisibilityEvidence.Request(1, "test", READ_REQUEST_ID, target()); + } + + private static TargetProof target() { + return new TargetProof( + binding().target().canonicalTenantId(), + binding().target().canonicalVersionId(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + } + + private static DraftCommitBinding multiOwnerBinding() { + return DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of( + new RevisionPayload( + "0", uuid("66666666-6666-4666-8666-666666666666"), Owner.WORLD_MANAGEMENT, "{}"), + new RevisionPayload( + "1", uuid("77777777-7777-4777-8777-777777777777"), Owner.ENTITY_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-1", + "ACTOR_SCOPE", + "actor-1", + "1"))); + } + + private static String resultVector(DraftCommitBinding binding) { + List> vector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + AffectedUnit unit = binding.affectedUnits(owner).getFirst(); + Map epoch = new LinkedHashMap<>(); + epoch.put("aggregateType", unit.aggregateType()); + epoch.put("aggregateId", unit.aggregateId()); + epoch.put("scopeType", unit.scopeType()); + epoch.put("scopeId", unit.scopeId()); + epoch.put("expectedEpoch", unit.expectedEpoch()); + epoch.put( + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()).add(java.math.BigInteger.ONE).toString()); + Map item = new LinkedHashMap<>(); + item.put("owner", owner.name()); + item.put("status", "APPLIED"); + item.put("commitId", COMMIT_ID.toString()); + item.put("bindingDigest", binding.digest()); + item.put( + "resultIdentity", owner == Owner.WORLD_MANAGEMENT ? "world-result" : "entity-result"); + item.put( + "resultBytesBase64", + Base64.getEncoder() + .encodeToString("world-result-bytes".getBytes(StandardCharsets.UTF_8))); + item.put("appliedEpochs", List.of(epoch)); + vector.add(item); + } + return canonical(new ObjectMapper().writeValueAsString(vector)); + } + + private static String canonical(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + private static UUID uuid(String value) { return UUID.fromString(value); } From b58dc2e9422d766a651eb49a97d3ec9b55558616 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:50:01 +1300 Subject: [PATCH 16/36] test(game-design): restore application-slot storage race coverage --- ...ame-authoring-publishing-and-activation.md | 6 + ...meDesignSourcePostgresIntegrationTest.java | 328 ++++++++++++++++++ 2 files changed, 334 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 4d072c1233..6baaea0156 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Draft application-slot storage race proof + +The existing Game Design source PostgreSQL owner test exercises both lifecycle-versus-slot orderings and both publication-selection-versus-slot orderings under Read Committed, Repeatable Read and Serializable. A committed lifecycle change or selection prevents a competing slot; a committed slot prevents the competing lifecycle change or selection. Stale snapshots refuse with the expected serialization failure. Logical Version fields remain unchanged where asserted; the winning storage interlock intentionally performs a no-op update, so this proof does not assert unchanged MVCC row versions across the winner. + +All sixteen owning native cases freshly pass with zero failures, errors or skips, including the four restored race cases and the twelve existing source-owner cases. Canonical formatting, style, Integration Checkstyle and SpotBugs pass. Passive capture identifies the one run-owned PostgreSQL container, records its lifecycle without endpoint probes and independently confirms its absence after completion. This proves current default-migration storage interlocks with controlled local source setup; it does not establish a creator credential, Account order or currentness, remote owner application, publication enablement, activation or a genuine Gameplay handoff. No production, migration or registration changes are included. + ### Template create and tenant-qualified updates The existing create service rejects a caller-supplied template ID before mapping or repository access. The repository updates only the exact tenant and template ID, never writes a replacement tenant binding and requires exactly one affected row before its tenant-qualified readback. No new public update API, migration, registration or hosted-content authority is introduced. 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 3cc7e645be..e5fb42bed3 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 @@ -9,10 +9,12 @@ import java.security.MessageDigest; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.SQLException; import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -957,6 +959,332 @@ private static String command(String id, String alias) { + "\"],\"actionTags\":[\"WORLD_BROWSE\"],\"effects\":[]}"; } + @Test + void rawLifecycleFirstRejectsSlotInsertAcrossSupportedIsolationLevels() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = fixture(); + var binding = storageBinding(local, "lifecycle-first"); + tx(local).executeWithoutResult(ignored -> claimStorageBinding(local, binding)); + try (var slot = storageConnection(local, isolation); + var lifecycle = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var slotSql = DSL.using(slot, SQLDialect.POSTGRES); + slotSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); + DSL.using(lifecycle, SQLDialect.POSTGRES) + .execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target().gameDesignVersionRowId()); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, binding)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + lifecycle.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + slot.rollback(); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl()) + .readApplicationSlot(local.target())) + .isEmpty(); + assertThat( + local + .dsl + .fetchSingle( + "SELECT version_state FROM version WHERE id = ?", + local.target().gameDesignVersionRowId()) + .get(0, String.class)) + .isEqualTo("RETIRED"); + } + } + } + + @Test + void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVersionFields() + throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = fixture(); + var binding = storageBinding(local, "slot-first"); + tx(local).executeWithoutResult(ignored -> claimStorageBinding(local, binding)); + var before = versionFields(local); + try (var slot = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var lifecycle = storageConnection(local, isolation); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var lifecycleSql = DSL.using(lifecycle, SQLDialect.POSTGRES); + lifecycleSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); + insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), binding); + var started = new java.util.concurrent.CountDownLatch(1); + var updating = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite( + () -> + lifecycleSql.execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target().gameDesignVersionRowId())); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + slot.commit(); + } + assertThat(updating.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + lifecycle.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl()) + .readApplicationSlot(local.target())) + .isPresent(); + } + } + } + + @Test + void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = fixture(); + var selected = synchronizedStorageSelection(local); + var later = storageBinding(local, "after-selection"); + tx(local).executeWithoutResult(ignored -> claimStorageBinding(local, later)); + var before = versionFields(local); + try (var slot = storageConnection(local, isolation); + var selection = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var slotSql = DSL.using(slot, SQLDialect.POSTGRES); + slotSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); + insertRawSelection(DSL.using(selection, SQLDialect.POSTGRES), selected); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, later)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + selection.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + slot.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl()) + .readApplicationSlot(local.target())) + .isEmpty(); + assertThat( + local.dsl().fetchCount(DSL.table("game_design_authored_draft_publish_selection"))) + .isEqualTo(1); + } + } + } + + @Test + void rawSlotFirstRejectsSelectionEvenWhenSelectionSnapshotPredatesSlot() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = fixture(); + var selected = synchronizedStorageSelection(local); + var later = storageBinding(local, "slot-before-selection"); + tx(local).executeWithoutResult(ignored -> claimStorageBinding(local, later)); + var before = versionFields(local); + try (var slot = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var selection = storageConnection(local, isolation); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var selectionSql = DSL.using(selection, SQLDialect.POSTGRES); + selectionSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); + insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), later); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSelection(selectionSql, selected)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + slot.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + selection.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl()) + .readApplicationSlot(local.target())) + .isPresent(); + assertThat( + local.dsl().fetchCount(DSL.table("game_design_authored_draft_publish_selection"))) + .isZero(); + } + } + } + + private int[] storageIsolationLevels() { + return new int[] { + Connection.TRANSACTION_READ_COMMITTED, + Connection.TRANSACTION_REPEATABLE_READ, + Connection.TRANSACTION_SERIALIZABLE + }; + } + + private Connection storageConnection(Fixture local, int isolation) throws SQLException { + var connection = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + connection.setSchema(local.schema()); + connection.setTransactionIsolation(isolation); + connection.setAutoCommit(false); + DSL.using(connection, SQLDialect.POSTGRES).execute("SET LOCAL lock_timeout = '10s'"); + return connection; + } + + private String failedStorageWrite(Runnable action) { + try { + action.run(); + throw new AssertionError("Conflicting storage write unexpectedly succeeded"); + } catch (org.jooq.exception.DataAccessException failure) { + Throwable cause = failure; + while (cause != null) { + if (cause instanceof SQLException sql) return sql.getSQLState(); + cause = cause.getCause(); + } + throw failure; + } + } + + private String versionFields(Fixture local) { + return local + .dsl + .fetchSingle( + "SELECT to_jsonb(v)::text FROM version v WHERE id = ?", + local.target().gameDesignVersionRowId()) + .get(0, String.class); + } + + private void insertRawSlot(DSLContext sql, DraftCommitBinding binding) { + sql.execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) VALUES (?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + } + + // Storage-only setup uses existing typed source and coordinator owners. It creates no + // creator credential, Account order, remote result or publication authority. + private static DraftCommitBinding storageBinding(Fixture fixture, String description) { + var current = fixture.coordinator().readVisibilityFence(fixture.target()); + String base = + current + .map(fence -> fence.commitId().toString()) + .orElseGet( + () -> + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId()); + String epoch = + current + .map( + fence -> + fixture + .sources() + .readSynchronized(fixture.target(), fence.commitId()) + .orElseThrow() + .command() + .sourceEpoch()) + .orElse("0"); + return binding(fixture.target(), base, null, epoch, null, false); + } + + private static void claimStorageBinding(Fixture fixture, DraftCommitBinding binding) { + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + fixture + .sources() + .claimReviewed( + binding, + reviewed.resolve( + fixture.target(), + net.firedevops.firemud.common.authoring.DraftBaseReference.parse( + binding.baseCommitId()))); + } + + private static TransactionTemplate tx(Fixture fixture) { + return fixture.write(); + } + + private static AuthoredDraftPublishSelection synchronizedStorageSelection(Fixture fixture) { + var binding = storageBinding(fixture, "storage-selected"); + var applied = apply(fixture, binding); + synchronize(fixture, binding, applied); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "controlled storage race", + binding.requestId(), + binding.commitId(), + binding.digest()); + return fixture.tx( + () -> + AuthoredDraftPublishSelection.capture( + intent, + fixture.target(), + fixture + .coordinator() + .requireSynchronizedPublicationEvidence( + fixture.target(), + binding.requestId(), + binding.commitId(), + binding.digest()))); + } + + private void insertRawSelection(DSLContext sql, AuthoredDraftPublishSelection selected) { + var target = selected.target(); + var intent = selected.intent(); + sql.execute( + "INSERT INTO game_design_authored_draft_publish_selection " + + "(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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + 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(), + selected.digest(), + selected.canonicalJson()); + } + private static Fixture fixture() { String schema = "gd_combined_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = From 476e73e339694013bd746bd1e182d99ff30420aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:55:23 +1300 Subject: [PATCH 17/36] test: qualify policy provenance and reviewed Draft storage claims --- ...ame-authoring-publishing-and-activation.md | 12 + ...meDesignSourcePostgresIntegrationTest.java | 211 ++++++++++++++++++ ...lmPolicySourcePostgresIntegrationTest.java | 148 ++++++++++++ 3 files changed, 371 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 501b388679..f7438dc378 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 @@ -18,6 +18,18 @@ The existing Game Design source PostgreSQL owner test exercises both lifecycle-v All sixteen owning native cases freshly pass with zero failures, errors or skips, including the four restored race cases and the twelve existing source-owner cases. Canonical formatting, style, Integration Checkstyle and SpotBugs pass. Passive capture identifies the one run-owned PostgreSQL container, records its lifecycle without endpoint probes and independently confirms its absence after completion. This proves current default-migration storage interlocks with controlled local source setup; it does not establish a creator credential, Account order or currentness, remote owner application, publication enablement, activation or a genuine Gameplay handoff. No production, migration or registration changes are included. +### Player-created policy descriptor provenance proof + +The existing realm-policy PostgreSQL owner test persists supported schema 2 and schema 3 player-created policies through the current reviewed source, genesis and synchronized fence. Each descriptor revision remains distinct from the authored revision identity. Independent repository reads and exact owner retry preserve the original canonical policy and application bytes; substituting a descriptor under the same commit and revision identity refuses without changing the prior snapshot. A real command-only source commit inherits the original policy provenance, and a later policy commit records the changed descriptor under its new authored identity while retaining the earlier policy. Schema 3 also preserves the authored initial actor core. + +All fourteen owning native invocations freshly pass with zero failures, errors or skips, including both restored schema cases and the twelve existing source-owner cases. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; one passively identified run-owned PostgreSQL container is independently absent after completion. This is controlled local source persistence, retry and provenance proof. It does not establish a creator credential, Account currentness, authenticated publication, a genuine immutable release, runtime realm creation, actor placement, activation or a Gameplay handoff. No production, installed migration or registration changes are included. + +### Reviewed Draft claim identity and rollback proof + +The existing Game Design source PostgreSQL owner test now exercises reviewed claim identity through actual fresh genesis and retained reviewed-base evidence. Exact retry preserves every retained column and MVCC row version in the claim, reviewed-base and owner-result rows. A valid changed command payload under the same request, commit and revision identities refuses without rewriting those rows. Rolling back a reviewed claim removes its claim, review and owner inventory together. Concurrent exact claims converge on one retained binding; competing requests for one commit and changed input for one request retain exactly one winner and its pending owner inventory. These claim cases leave the application slot unopened. + +All twenty-one owning native cases freshly pass with zero failures, errors or skips, including the five restored claim cases and the sixteen existing source and storage-race cases. Canonical formatting, style, Integration Checkstyle and SpotBugs pass. Passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. The concurrent launch latches establish the submitted competing operations and retained outcomes; they do not independently measure precommit blocking. This is current-default local storage and reviewed-source proof, without authenticated creator or issuer, Account currentness, remote owner application, public publication enablement, a genuine immutable release, activation or a Gameplay handoff. No production code, installed migration, finalizer, recovery composer or registration is changed. + ### Template create and tenant-qualified updates The existing create service rejects a caller-supplied template ID before mapping or repository access. The repository updates only the exact tenant and template ID, never writes a replacement tenant binding and requires exactly one affected row before its tenant-qualified readback. No new public update API, migration, registration or hosted-content authority is introduced. 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 e5fb42bed3..572a76ca1d 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 @@ -14,6 +14,8 @@ 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; @@ -58,6 +60,215 @@ class GameDesignSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void exactReviewedClaimReplayPreservesAllRetainedRowsAndChangedInputCannotRewriteThem() { + var local = fixture(); + var original = storageBinding(local, "reviewed-claim"); + local.tx( + () -> { + claimStorageBinding(local, original); + return null; + }); + var retained = reviewedClaimRows(local); + local.tx( + () -> { + claimStorageBinding(local, original); + return null; + }); + assertThat(reviewedClaimRows(local)).isEqualTo(retained); + var changed = changedClaimInput(original); + assertThatThrownBy( + () -> + local.tx( + () -> { + claimStorageBinding(local, changed); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + assertThat(reviewedClaimRows(local)).isEqualTo(retained); + assertReviewedClaimInventory(local, original); + } + + @Test + void reviewedClaimAndItsOwnerInventoryRollBackWithoutRetainingReviewEvidence() { + var local = fixture(); + var binding = storageBinding(local, "rolled-back-reviewed-claim"); + local + .write() + .executeWithoutResult( + status -> { + claimStorageBinding(local, binding); + status.setRollbackOnly(); + }); + assertThat(local.coordinator().read(local.target(), binding.requestId())).isEmpty(); + assertThat(new GameDesignReviewedBaseRepository(local.dsl()).read(binding)).isEmpty(); + assertThat(local.coordinator().readApplicationSlot(local.target())).isEmpty(); + for (String table : + List.of( + "game_design_draft_commit", + "game_design_draft_commit_owner_result", + "game_design_reviewed_draft_base")) { + assertThat(local.dsl().fetchCount(DSL.table(table))).isZero(); + } + } + + @Test + void concurrentExactReviewedClaimsConvergeOnOneBindingAndOwnerInventory() throws Exception { + var local = fixture(); + var binding = storageBinding(local, "concurrent-exact-reviewed"); + var claims = concurrentReviewedClaims(local, binding, binding); + assertThat(claims) + .allSatisfy( + claim -> { + assertThat(claim.failure()).isNull(); + assertThat(claim.binding()).isEqualTo(binding); + }); + assertReviewedClaimInventory(local, binding); + } + + @Test + void concurrentRequestsCannotAliasOneReviewedCommitOrRetainLosingOwnerRows() throws Exception { + var local = fixture(); + var first = storageBinding(local, "concurrent-commit-identity"); + var second = + DraftCommitBinding.create( + first.target(), + UUID.randomUUID(), + first.commitId(), + first.baseCommitId(), + first.revisions(), + first.affectedUnits()); + var claims = concurrentReviewedClaims(local, first, second); + var winner = soleReviewedClaimWinner(claims); + var losingRequest = winner.equals(first) ? second.requestId() : first.requestId(); + assertThat(local.coordinator().read(local.target(), losingRequest)).isEmpty(); + assertReviewedClaimInventory(local, winner); + } + + @Test + void concurrentChangedReviewedInputCannotShareOneRequestIdentity() throws Exception { + var local = fixture(); + var first = storageBinding(local, "concurrent-request-input"); + var changed = changedClaimInput(first); + assertThat(changed.digest()).isNotEqualTo(first.digest()); + var claims = concurrentReviewedClaims(local, first, changed); + assertReviewedClaimInventory(local, soleReviewedClaimWinner(claims)); + } + + private static DraftCommitBinding changedClaimInput(DraftCommitBinding original) { + var revision = original.revisions().getFirst(); + // Preserve every request/commit/revision identity while changing a valid command alias. + return DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of( + new RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + CommandSource.upsertPayload(command("look", "changed")))), + original.affectedUnits()); + } + + private static List> reviewedClaimRows(Fixture local) { + return List.of( + local + .dsl() + .fetch( + "SELECT t.*, t.xmin::text AS retained_xmin FROM game_design_draft_commit t ORDER BY request_id"), + local + .dsl() + .fetch( + "SELECT t.*, t.xmin::text AS retained_xmin FROM game_design_draft_commit_owner_result t ORDER BY request_id"), + local + .dsl() + .fetch( + "SELECT t.*, t.xmin::text AS retained_xmin FROM game_design_reviewed_draft_base t ORDER BY request_id")); + } + + private static void assertReviewedClaimInventory(Fixture local, DraftCommitBinding binding) { + var persisted = local.coordinator().read(local.target(), binding.requestId()).orElseThrow(); + assertThat(persisted.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(persisted.ownerStates()).containsOnlyKeys(Owner.GAME_DESIGN_CONTROL_PLANE); + assertThat(persisted.ownerStates().values()) + .allSatisfy( + state -> { + assertThat(state.status()) + .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.NOT_ATTEMPTED); + assertThat(state.outcome()).isEmpty(); + }); + assertThat(new GameDesignReviewedBaseRepository(local.dsl()).read(binding)).isPresent(); + assertThat(local.coordinator().readApplicationSlot(local.target())).isEmpty(); + for (String table : + List.of( + "game_design_draft_commit", + "game_design_draft_commit_owner_result", + "game_design_reviewed_draft_base")) { + assertThat(local.dsl().fetchCount(DSL.table(table))).isEqualTo(1); + } + } + + private static List concurrentReviewedClaims( + Fixture local, DraftCommitBinding first, DraftCommitBinding second) throws Exception { + var ready = new CountDownLatch(2); + var launch = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var left = executor.submit(() -> reviewedClaimAttempt(local, first, ready, launch)); + var right = executor.submit(() -> reviewedClaimAttempt(local, second, ready, launch)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + launch.countDown(); + return List.of(left.get(20, TimeUnit.SECONDS), right.get(20, TimeUnit.SECONDS)); + } finally { + launch.countDown(); + executor.shutdownNow(); + } + } + + private static ReviewedClaimAttempt reviewedClaimAttempt( + Fixture local, DraftCommitBinding binding, CountDownLatch ready, CountDownLatch launch) + throws InterruptedException { + ready.countDown(); + if (!launch.await(20, TimeUnit.SECONDS)) + throw new IllegalStateException("Reviewed claim launch timed out"); + try { + var persisted = + local.tx( + () -> { + claimStorageBinding(local, binding); + return local + .coordinator() + .read(local.target(), binding.requestId()) + .orElseThrow() + .binding(); + }); + return new ReviewedClaimAttempt(persisted, null); + } catch (RuntimeException failure) { + return new ReviewedClaimAttempt(null, failure); + } + } + + private static DraftCommitBinding soleReviewedClaimWinner(List claims) { + assertThat(claims.stream().filter(claim -> claim.failure() == null)).hasSize(1); + assertThat(claims.stream().filter(claim -> claim.failure() != null)) + .singleElement() + .satisfies( + claim -> + assertThat(claim.failure()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT")); + return claims.stream() + .filter(claim -> claim.failure() == null) + .findFirst() + .orElseThrow() + .binding(); + } + + private record ReviewedClaimAttempt(DraftCommitBinding binding, RuntimeException failure) {} + @Test void firstReferenceRejectsStaleOrdinaryByteUpdate() throws Exception { assertFirstReferenceRejectsStaleUpdate(false, false); 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 ddceffa259..b23adeb398 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 @@ -38,6 +38,8 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -55,6 +57,130 @@ class RealmPolicySourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @ParameterizedTest + @ValueSource(ints = {2, 3}) + void playerCreatedPolicyDescriptorPersistsAndReplaysWithIndependentAuthoredProvenance( + int schemaVersion) { + var fixture = freshFixture(); + String descriptorRevisionId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + String policyBytes = playerCreatedPolicy(schemaVersion, descriptorRevisionId); + String authoredPayload = policyRevision(policyBytes); + var binding = + policyMutationBinding( + fixture, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, authoredPayload))); + start(fixture, binding); + UUID authoredRevisionId = binding.revisions().getFirst().revisionId(); + + var applied = fixture.tx(() -> fixture.sources().apply(binding)); + synchronize(fixture, binding, applied); + var original = applied.policy().orElseThrow().snapshot(); + assertThat(original.policies()).hasSize(1); + var authored = original.policies().getFirst(); + assertThat(authored.commitId()).isEqualTo(binding.commitId()); + assertThat(authored.revisionId()).isEqualTo(authoredRevisionId); + assertThat(authoredRevisionId.toString()).isNotEqualTo(descriptorRevisionId); + assertThat(authored.policy().canonicalJson()).isEqualTo(policyBytes); + if (schemaVersion == 3) { + assertThat(authored.policy().initialActorCore().displayName()).isEqualTo("Wayfarer"); + assertThat(authored.policy().initialActorCore().dispositionKey()).isEqualTo("newcomer"); + } + + String applicationJson = + fixture + .dsl() + .fetchSingle( + "SELECT snapshot_json 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()) + .get(0, String.class); + assertThat(applicationJson).isEqualTo(original.canonicalJson()); + var stored = + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow(); + assertThat(stored.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(stored.policies().getFirst().policy().canonicalJson()).isEqualTo(policyBytes); + + var retry = fixture.tx(() -> fixture.sources().apply(binding)); + assertThat(retry.ownerOutcome()).isEqualTo(applied.ownerOutcome()); + assertThat(retry.policy().orElseThrow().canonicalBytes()) + .containsExactly(applied.policy().orElseThrow().canonicalBytes()); + + var originalRevision = binding.revisions().getFirst(); + var changedSameIdentity = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + originalRevision.revisionOrder(), + originalRevision.revisionId(), + originalRevision.owner(), + policyRevision( + playerCreatedPolicy( + schemaVersion, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")))), + binding.affectedUnits()); + assertThat(changedSameIdentity.digest()).isNotEqualTo(binding.digest()); + assertThatThrownBy(() -> fixture.tx(() -> fixture.policies().apply(changedSameIdentity))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("POLICY_COMMIT_BINDING_CONFLICT"); + assertThat( + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(original.canonicalBytes()); + + var inheritedBinding = commandOnlyBinding(fixture, binding.commitId(), "0"); + start(fixture, inheritedBinding); + var inheritedApplication = fixture.tx(() -> fixture.sources().apply(inheritedBinding)); + synchronize(fixture, inheritedBinding, inheritedApplication); + var inherited = + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(inheritedBinding.target(), inheritedBinding.commitId()) + .orElseThrow(); + assertThat(inherited.policies()).hasSize(1); + assertThat(inherited.policies().getFirst().commitId()).isEqualTo(binding.commitId()); + assertThat(inherited.policies().getFirst().revisionId()).isEqualTo(authoredRevisionId); + assertThat(inherited.policies().getFirst().policy().canonicalJson()).isEqualTo(policyBytes); + + String changedPolicyBytes = + playerCreatedPolicy(schemaVersion, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var changedBinding = + policyMutationBinding( + fixture, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyRevision(changedPolicyBytes)))); + start(fixture, changedBinding); + var changed = fixture.tx(() -> fixture.sources().apply(changedBinding)); + synchronize(fixture, changedBinding, changed); + var changedPolicy = changed.policy().orElseThrow().snapshot().policies().getFirst(); + assertThat(changedPolicy.commitId()).isEqualTo(changedBinding.commitId()); + assertThat(changedPolicy.revisionId()) + .isEqualTo(changedBinding.revisions().getFirst().revisionId()); + assertThat(changedPolicy.policy().canonicalJson()).isEqualTo(changedPolicyBytes); + assertThat(changedPolicy.policy().canonicalJson()).isNotEqualTo(policyBytes); + assertThat( + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow() + .policies() + .getFirst() + .policy() + .canonicalJson()) + .isEqualTo(policyBytes); + } + @Test void freshGenesisCreatesNoFakeCommitAndFirstActualPolicyCommitReplaysExactly() { var fixture = freshFixture(); @@ -828,6 +954,28 @@ private static GameDesignPublicationOperation publication(Fixture fixture) { }); } + private static String playerCreatedPolicy(int schemaVersion, String descriptorRevisionId) { + String actorCore = + schemaVersion == 3 + ? "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}," + : ""; + String json = + "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"99999999-9999-4999-8999-999999999999\",\"descriptorRevisionId\":\"" + + descriptorRevisionId + + "\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\"," + + actorCore + + "\"publicProduction\":false,\"realmDisplayName\":\"Player Realm\",\"realmSlug\":\"player-realm\",\"schemaVersion\":" + + schemaVersion + + ",\"stateScope\":\"ISOLATED\",\"visible\":true,\"worldDisplayName\":\"Player World\",\"worldSlug\":\"player-world\"}"; + return RealmEntryPolicy.parse(json, new ObjectMapper()).canonicalJson(); + } + + private static String policyRevision(String policyBytes) { + return "{\"logicalRevisionId\":\"player-created-realm-policy\",\"policy\":" + + policyBytes + + ",\"revisionKind\":\"REALM_ENTRY_POLICY\"}"; + } + private static DraftCommitBinding policyBinding( Fixture fixture, String realm, boolean production) { TargetProof target = fixture.target(); From 4f51bfc71717157ec3ca86a4845c38ab1d2aefab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:39:53 +1300 Subject: [PATCH 18/36] Remove duplicate capture-fixture import with canonical formatter --- .../draft/GameDesignSourcePostgresIntegrationTest.java | 1 - 1 file changed, 1 deletion(-) 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 97a3901169..c0b8e6fd55 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 @@ -42,7 +42,6 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSnapshot; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; -import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; From d0064be637a40c1f17e8209796a3a2e6951f2929 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:00:41 +1300 Subject: [PATCH 19/36] Reuse canonical watcher helpers in selected owner lifecycle tests --- ...electedOwnerIntakeClientLifecycleTest.java | 74 ++----------------- ...edCoreAndSpawnReadClientLifecycleTest.java | 74 ++----------------- 2 files changed, 12 insertions(+), 136 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 7610d66f8e..58ce702cc1 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.common.account.sourceintake; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitBlockedReloadCallback; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitCondition; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitLatch; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.setWatcher; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.watcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -11,16 +16,13 @@ import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; -import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; -import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BooleanSupplier; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -72,7 +74,6 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( AbstractReloadingBlockingGrpcClient clientUnderTest = client; originalWatcher = watcher(client); - Set activeCallbacks = activeCallbacks(originalWatcher); TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); TlsCertificateWatcher delegatedWatcher = originalWatcher; doAnswer( @@ -117,7 +118,7 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); - Thread callback = awaitBlockedReloadCallback(activeCallbacks); + Thread callback = awaitBlockedReloadCallback(originalWatcher); assertThat(callback).isNotNull(); releaseClientMonitor.countDown(); @@ -192,69 +193,6 @@ ClientHandle create( } } - private static Thread awaitBlockedReloadCallback(Set activeCallbacks) - throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (System.nanoTime() < deadline) { - for (Thread callback : activeCallbacks) { - if (callback.getState() == Thread.State.BLOCKED - && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { - return callback; - } - } - Thread.sleep(10); - } - return null; - } - - private static boolean hasFrame(Thread thread, String className, String methodName) { - for (StackTraceElement frame : thread.getStackTrace()) { - if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { - return true; - } - } - return false; - } - - private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (!condition.getAsBoolean() && System.nanoTime() < deadline) { - Thread.sleep(10); - } - assertThat(condition.getAsBoolean()).isTrue(); - } - - private static void awaitLatch(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - } - - private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - return (TlsCertificateWatcher) field.get(client); - } - - private static void setWatcher( - AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - field.set(client, watcher); - } - - @SuppressWarnings("unchecked") - private static Set activeCallbacks(TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); - field.setAccessible(true); - return (Set) field.get(watcher); - } - private static CommonGrpcClientProperties tls(Path directory) throws Exception { CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java index bfe1d361c0..bf9f40dc20 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.common.gamedesign; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitBlockedReloadCallback; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitCondition; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitLatch; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.setWatcher; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.watcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -11,16 +16,13 @@ import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; -import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; -import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BooleanSupplier; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; @@ -91,7 +93,6 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( AbstractReloadingBlockingGrpcClient clientUnderTest = client; originalWatcher = watcher(client); - Set activeCallbacks = activeCallbacks(originalWatcher); TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); TlsCertificateWatcher delegatedWatcher = originalWatcher; doAnswer( @@ -136,7 +137,7 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); - Thread callback = awaitBlockedReloadCallback(activeCallbacks); + Thread callback = awaitBlockedReloadCallback(originalWatcher); assertThat(callback).isNotNull(); releaseClientMonitor.countDown(); @@ -313,69 +314,6 @@ ClientHandle create( } } - private static Thread awaitBlockedReloadCallback(Set activeCallbacks) - throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (System.nanoTime() < deadline) { - for (Thread callback : activeCallbacks) { - if (callback.getState() == Thread.State.BLOCKED - && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { - return callback; - } - } - Thread.sleep(10); - } - return null; - } - - private static boolean hasFrame(Thread thread, String className, String methodName) { - for (StackTraceElement frame : thread.getStackTrace()) { - if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { - return true; - } - } - return false; - } - - private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (!condition.getAsBoolean() && System.nanoTime() < deadline) { - Thread.sleep(10); - } - assertThat(condition.getAsBoolean()).isTrue(); - } - - private static void awaitLatch(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - } - - private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - return (TlsCertificateWatcher) field.get(client); - } - - private static void setWatcher( - AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - field.set(client, watcher); - } - - @SuppressWarnings("unchecked") - private static Set activeCallbacks(TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); - field.setAccessible(true); - return (Set) field.get(watcher); - } - private static CommonGrpcClientProperties tls(Path directory) throws Exception { CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); tls.setCertChain(entityCertificate(directory).toString()); From afef33581d9eb30b39c5e42262925719a653e613 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 08:23:06 +1300 Subject: [PATCH 20/36] Preserve primary selected-source fixture failures during cleanup --- ...takeSourceReservationPostgresIntegrationTest.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index f3d463cbf6..03c2041e73 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -17,13 +17,15 @@ /** PostgreSQL installation proof for V1007's additive selected-owner source reservations. */ class AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest { @Test - void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() { + void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() + throws Exception { var fixture = new AccountPostgresIntegrationFixture(); - try { + try (AutoCloseable fixtureCleanup = fixture::stop) { fixture.start(); String schema = "selected_owner_source_" + UUID.randomUUID().toString().replace("-", ""); JdbcTemplate admin = new JdbcTemplate(fixture.dataSource()); - try { + try (AutoCloseable schemaCleanup = + () -> admin.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE")) { admin.execute("CREATE SCHEMA " + quotedSchema(schema)); DriverManagerDataSource source = fixture.dataSource(schema); JdbcTemplate jdbc = new JdbcTemplate(source); @@ -124,11 +126,7 @@ void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWit assertMalformedReservationCreatesNoSourceRows(jdbc); assertThat(retainedParentRows(jdbc)).isEqualTo(retainedParent); - } finally { - admin.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE"); } - } finally { - fixture.stop(); } } From 3f19a1417b37e615d0ba9d829c408d568ef026e5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:30:40 +1300 Subject: [PATCH 21/36] Record automatic repack failure separately from receiving proof --- design/project-management/ai-observations.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b4a61084ac..ebc1df1aef 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -206,3 +206,9 @@ Entry format: - 2026-10-18: In the CI maintenance PR #3264 Hosted retry, an ad hoc multiline shell read a snapshot file before its producer finished; the JSON check failed but the following provider POST still executed because that shell did not enable errexit. The prior and completed fresh snapshots both showed no active Hosted request, so no conflict was observed. Keep a dependent external mutation in a separate tool call after checking producer completion and validated output; use explicit `set -euo pipefail` for dependent shell batches. - 2026-10-18: CodeRabbit full review 5560170943 for PR #3264 emitted a complete 1/1 publication with one outside-diff Major but no bounded actionable-comment count. The existing manual adoption correctly refused automatic attribution with `Hosted publication has no unique bounded actionable-comment count`. Exact trigger 6241278398, reviewed head `187ab53426caf78cd6a01b61e092b800186aaec2`, provider result and accepted obligation were retained in the CI validation throughput controller job history without invented Hosted credit; no controller adapter change was made in this CI patch. Reconsider format support only in a separately scoped controller maintenance task. + +- `2026-10-18`: Keep automatic Git repack failures separate from local commit proof + - Context: The #3248 private-parent receiving commit `029b6299b0ec63a6cd0a1cd30197cc7b3ca56ded` triggered automatic Git maintenance in the shared repository. + - Observation: The commit succeeded, and background repack reported `fatal: bad object refs/remotes/origin/codex/document-original-world-preparation-20261015` and `fatal: failed to run repack`. The exact cause and repository object health remain unknown. + - Expected pattern: Record commit and receiving evidence separately from background maintenance results. Investigate only under qualified shared-repository maintenance or when an actual delivery blocker requires it; `gc.log` or unreachable-object warnings do not authorize cleanup. + - Status and reconsideration: The commit retained prospective tree `733ed58d9390a5ba00e24088435af7b847567527`, all 84 child-owned postimages and the deletion, and all 12 qualified incoming blobs. Evidence is in Controller current-gameplay update 2151, `private-parent-carry-via-09e-verification.json`, and `receive-qualified-private-cli1-parent.patch` under the private #3248 local current-parent-carry evidence. Revisit if a qualified maintenance pass identifies the cause or the failure blocks delivery. From 78a4fa8a320f1d5d28449f44c1acbef57fd25225 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:13:13 +1300 Subject: [PATCH 22/36] Preserve unenrolled branding capture history and reuse client lifecycle guards --- design/project-management/ai-observations.md | 20 +- ...pcSelectedOwnerIntakeSourceReadClient.java | 34 +- .../GrpcSelectedOwnerIntakeSourceClient.java | 32 +- .../GameDesignSourceRepository.java | 2 +- ...BrandingSourcePostgresIntegrationTest.java | 387 ++++++++++++++---- 5 files changed, 347 insertions(+), 128 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index deae54e213..668f9b6ae9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -115,11 +115,20 @@ Entry format: - Expected pattern: Compare every patch target with the pinned worktree path, then inspect the first written file at that absolute destination before continuing. This destination check remains manual. - Reconsideration trigger: enforce destination verification at the native patch boundary, or repeat measurement disproves the risk; completion of migration review alone does not resolve it. -- `2026-10-15`: Allocate forward migrations against the actual resolved Flyway history, including shared Saga resources and later service-owned migrations. The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history. The receiving Account parent already reaches V1005, while Saga reaches V1002. Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. +- `2026-10-15`: Allocate forward migrations against the resolved combined Flyway history + - Context: The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history, including shared Saga resources and later service-owned migrations. + - Observation: The receiving Account parent already reaches V1005, while Saga reaches V1002. + - Expected pattern: Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. -- `2026-10-16`: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. A Document source gate automatically acquired the lock before its delayed peer completion message arrived; busy admission remains unrun proof. +- `2026-10-16`: Use bounded admission for shared heavy runs + - Context: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. + - Observation: A Document source gate automatically acquired the lock before its delayed peer completion message arrived. + - Expected pattern: Treat busy admission as unrun proof. -- `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content. +- `2026-10-16`: Bound conflict markers and inspect reconstructed files + - Context: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. + - Observation: Native `git merge-file` reconstruction from the exact parents recovered the complete files; a clean whitespace check alone cannot detect lost content. + - Expected pattern: Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing. - `2026-10-15`: Preserve receiver status when relocating inherited tracker proof - Context: the local #3224 parent reconciliation relocated inherited LOGIN proof into a dedicated section. Selecting the complete incoming tracker plus one receiver proof paragraph also displaced the receiver's first-party denial and historical-proof qualifications. The candidate had not been published. @@ -127,7 +136,10 @@ Entry format: - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. -- `2026-10-16`: Check both public mapping directions when an internal read requires an identity distinct from its original operation. The launch-association receiver retained that guard while a refactor removed it from the request encoder; the receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. +- `2026-10-16`: Check both public mapping directions for transport identity + - Context: An internal read requires an identity distinct from its original operation. The launch-association receiver retained the guard while a refactor removed it from the request encoder. + - Observation: The receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. + - Expected pattern: Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. - `2026-10-16`: Report source validation separately from packaged smoke - Context: PR #3224 had a successful Validation result and a separate runtime-image Smoke failure in run [38844094461](https://github.com/benhook1013/FireMUD/actions/runs/38844094461); the retained local job record showed Gateway and TCP Proxy public readiness intentionally out of service after the bounded Compose wait. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java index 368673e629..5436e6cefd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit file-backed mTLS client for preliminary selected-owner source-scope confirmation. */ public final class GrpcSelectedOwnerIntakeSourceReadClient @@ -26,8 +25,6 @@ public final class GrpcSelectedOwnerIntakeSourceReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcSelectedOwnerIntakeSourceReadClient( ServiceEndpointsProperties endpoints, @@ -44,22 +41,17 @@ public GrpcSelectedOwnerIntakeSourceReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Account selected-owner read client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account selected-owner read stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account selected-owner read client is closed", + "Account selected-owner read stub unavailable"); } /** Returns Account's exact preliminary confirmation after authenticating its server identity. */ @Override public SelectedOwnerIntakeSourceReadEvidence read( SelectedOwnerIntakeSourceReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) - throw new IllegalStateException("Account selected-owner read must run outside SQL"); + requireNoAmbientSql("Account selected-owner read must run outside SQL"); Objects.requireNonNull(request, "source-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException( @@ -98,23 +90,11 @@ protected String defaultTarget() { .withCompression("gzip"); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - private AccountSelectedOwnerIntakeSourceReadServiceGrpc .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) - throw new IllegalStateException( - "Account selected-owner read client is not initialized and available"); - return currentStub; + return requireInitializedStub( + "Account selected-owner read client is not initialized and available"); } private static CommonGrpcClientProperties requireFileBackedMtls( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java index 4c86b7343f..d3c7966bce 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java @@ -16,7 +16,6 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit file-backed mTLS client for complete selected-owner source content. */ public final class GrpcSelectedOwnerIntakeSourceClient @@ -27,8 +26,6 @@ public final class GrpcSelectedOwnerIntakeSourceClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcSelectedOwnerIntakeSourceClient( ServiceEndpointsProperties endpoints, @@ -45,22 +42,15 @@ public GrpcSelectedOwnerIntakeSourceClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Game Design source client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) throw new IllegalStateException("Game Design source stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce("Game Design source client is closed", "Game Design source stub unavailable"); } /** Reads exact selected source content after authenticating the configured Game Design peer. */ @Override public SelectedOwnerIntakeSourceContent read( SelectedOwnerIntakeSourceReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) - throw new IllegalStateException( - "Game Design selected-owner source read must run outside SQL"); + requireNoAmbientSql("Game Design selected-owner source read must run outside SQL"); Objects.requireNonNull(request, "selected-owner source-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException( @@ -99,23 +89,11 @@ protected String defaultTarget() { .withCompression("gzip"); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - private GameDesignSelectedOwnerIntakeSourceServiceGrpc .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) - throw new IllegalStateException( - "Game Design selected-owner source client is not initialized and available"); - return currentStub; + return requireInitializedStub( + "Game Design selected-owner source client is not initialized and available"); } private static CommonGrpcClientProperties requireFileBackedMtls( 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 4a1d3adecf..705f1cfbb3 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 @@ -390,7 +390,7 @@ public Optional readCapture(GameDesignPublicationOperation operation) { || policy.isEmpty() || (asset.isEmpty() && !historicalOperation) || (gameplayCapture.isEmpty() && !historicalOperation && !historicalGameplay) - || (brand.isEmpty() && (!historicalOperation || brandingSourceEnrolled)) + || (brand.isEmpty() && brandingSourceEnrolled) || (templateSourceEnrolled && templateConfig.isEmpty() && !historicalTemplate)) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index c78b1291bb..1bd265987f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -16,14 +17,27 @@ import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; import net.firedevops.firemud.gamedesign.publication.BrandingSourceRepository; +import net.firedevops.firemud.gamedesign.publication.CommandSourceRepository; +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.GameplayRuleSourceRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; @@ -135,75 +149,7 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH @Test void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesis() { var f = fixture("1025"); - var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); - f.tx.executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - coordinator.claim(original); - var policyGenesis = - new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) - .readGenesis(f.target) - .orElseThrow(); - var commands = - new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); - var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); - var assetGenesis = - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(f.dsl) - .readGenesis(f.target) - .orElseThrow(); - var gameplayGenesis = - new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) - .readGenesis(f.target) - .orElseThrow(); - var templateGenesis = - new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository( - f.dsl) - .readGenesis(f.target) - .orElseThrow(); - var reviewedEvidence = - GameDesignReviewedBaseEvidence.genesis( - new GameDesignSourceRepository.Genesis( - policyGenesis, - commandGenesis, - Optional.of(assetGenesis), - Optional.of(gameplayGenesis), - Optional.of(templateGenesis))); - insertReviewedBaseV2(f.dsl, original, reviewedEvidence); - coordinator.claimApplicationSlot(original); - coordinator.markOwnerInProgress( - original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = commands.apply(original).orElseThrow(); - var out = new java.io.ByteArrayOutputStream(); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, "game-design-control-plane-command-application/v1"); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, original.canonicalBytes()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, applied.canonicalBytes()); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - original.commitId(), - original.digest(), - applied.resultIdentity(), - out.toByteArray(), - List.of(applied.commandAppliedEpoch())); - coordinator.recordOwnerOutcome(original, outcome); - coordinator.advanceVisibilityFence( - original, - new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); - commands.captureSynchronized(original); - new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) - .captureSynchronized(original); - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(f.dsl) - .captureSynchronized(original); - new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) - .captureSynchronized(original); - new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository(f.dsl) - .captureSynchronized(original); - coordinator.releaseApplicationSlot(original); - }); + var original = retainPreBrandingSourceCommit(f); var originalSources = List.of( "command_source", @@ -341,6 +287,103 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } + @Test + void retainedV2CaptureWithoutBrandingRemainsReadableAsPartialHistory() throws Exception { + var f = fixture("1025"); + var original = retainPreBrandingSourceCommit(f); + var operation = retainPreBrandingV2Capture(f, original); + var captureRows = + Map.of( + "command", + retainedCapture(f, "game_design_command_source_capture", operation.workflowId()), + "realm_policy", + retainedCapture(f, "game_design_realm_policy_capture", operation.workflowId()), + "asset", + retainedCapture(f, "game_design_asset_source_capture", operation.workflowId()), + "template_config", + retainedCapture(f, "game_design_template_config_source_capture", operation.workflowId())); + var operationBefore = + f.dsl.fetchSingle( + "SELECT request_bytes, xmin::text AS row_xmin FROM game_design_publication_operation " + + "WHERE publish_workflow_id = ?", + operation.workflowId()); + byte[] operationBytes = operationBefore.get("request_bytes", byte[].class); + + f.migrate(); + + var operationAfter = + f.dsl.fetchSingle( + "SELECT request_bytes, xmin::text AS row_xmin FROM game_design_publication_operation " + + "WHERE publish_workflow_id = ?", + operation.workflowId()); + assertThat(operationAfter.get("request_bytes", byte[].class)).containsExactly(operationBytes); + assertThat(operationAfter.get("row_xmin", String.class)) + .isEqualTo(operationBefore.get("row_xmin", String.class)); + captureRows.forEach( + (family, before) -> + assertRetainedCapture( + f, + switch (family) { + case "command" -> "game_design_command_source_capture"; + case "realm_policy" -> "game_design_realm_policy_capture"; + case "asset" -> "game_design_asset_source_capture"; + case "template_config" -> "game_design_template_config_source_capture"; + default -> throw new IllegalStateException("Unknown capture family " + family); + }, + operation.workflowId(), + before)); + + var retained = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); + assertThat(retained.branding()).isEmpty(); + assertThat(retained.gameplay()).isEmpty(); + assertThat(retained.command().canonicalBytes()) + .containsExactly(captureRows.get("command").captureBytes()); + assertThat(retained.policy().canonicalBytes()) + .containsExactly(captureRows.get("realm_policy").captureBytes()); + assertThat(retained.asset().orElseThrow().canonicalBytes()) + .containsExactly(captureRows.get("asset").captureBytes()); + assertThat(retained.templateConfig().orElseThrow().canonicalBytes()) + .containsExactly(captureRows.get("template_config").captureBytes()); + assertThatThrownBy( + () -> f.tx.execute(ignored -> new GameDesignSourceRepository(f.dsl).freeze(operation))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + + @Test + void retainedCaptureWithoutBrandingStillFailsForBrandingEnrolledTarget() throws Exception { + var f = fixture(null); + var operation = retainFreshV2CaptureWithoutBranding(f); + assertThat(new BrandingSourceRepository(f.dsl).readGenesis(f.target)).isPresent(); + for (String table : + List.of( + "game_design_command_source_capture", + "game_design_realm_policy_capture", + "game_design_asset_source_capture", + "game_design_gameplay_rule_source_capture", + "game_design_template_config_source_capture")) { + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM " + table + " WHERE publish_workflow_id = ?", + operation.workflowId()) + .get(0, Long.class)) + .as(table) + .isEqualTo(1L); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_branding_source_capture " + + "WHERE publish_workflow_id = ?", + operation.workflowId()) + .get(0, Long.class)) + .isZero(); + assertThatThrownBy(() -> new GameDesignSourceRepository(f.dsl).readCapture(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); + } + @Test void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { var f = fixture(null); @@ -372,6 +415,212 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { .isEmpty(); } + private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { + var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(original); + var policyGenesis = new RealmPolicySourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var commands = new CommandSourceRepository(f.dsl); + var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); + var assetGenesis = new AssetSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var gameplayGenesis = + new GameplayRuleSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var templateGenesis = + new TemplateConfigSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var reviewedEvidence = + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis( + policyGenesis, + commandGenesis, + Optional.of(assetGenesis), + Optional.of(gameplayGenesis), + Optional.of(templateGenesis))); + insertReviewedBaseV2(f.dsl, original, reviewedEvidence); + coordinator.claimApplicationSlot(original); + coordinator.markOwnerInProgress( + original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = commands.apply(original).orElseThrow(); + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-control-plane-command-application/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, original.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, applied.canonicalBytes()); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + original.commitId(), + original.digest(), + applied.resultIdentity(), + out.toByteArray(), + List.of(applied.commandAppliedEpoch())); + coordinator.recordOwnerOutcome(original, outcome); + coordinator.advanceVisibilityFence( + original, + new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); + commands.captureSynchronized(original); + new RealmPolicySourceRepository(f.dsl).captureSynchronized(original); + new AssetSourceRepository(f.dsl).captureSynchronized(original); + new GameplayRuleSourceRepository(f.dsl).captureSynchronized(original); + new TemplateConfigSourceRepository(f.dsl).captureSynchronized(original); + coordinator.releaseApplicationSlot(original); + }); + return original; + } + + private GameDesignPublicationOperation retainPreBrandingV2Capture( + Fixture f, DraftCommitBinding original) throws Exception { + var seed = + IsolatedPublicationOperationFixtures.fresh(f.target, original.commitId().toString()); + var selectedCommit = seed.account().input().selection().selectedCommit(); + var world = seed.world(); + return Objects.requireNonNull( + f.tx.execute( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + var originalSources = + sources.readSynchronized(f.target, original.commitId()).orElseThrow(); + var originalOutcome = + coordinator.read(f.target, original.requestId()).orElseThrow(); + var reviewed = GameDesignReviewedBaseEvidence.authored(originalSources, originalOutcome); + sources.claimReviewed(selectedCommit, reviewed); + coordinator.claimApplicationSlot(selectedCommit); + coordinator.markOwnerInProgress( + selectedCommit, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + var epochs = + selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).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, + selectedCommit.commitId(), + selectedCommit.digest(), + "ISOLATED-world-applied", + world.appliedResultBytes(), + epochs); + coordinator.recordOwnerOutcome(selectedCommit, outcome); + coordinator.advanceVisibilityFence( + selectedCommit, + new DraftCommitCoordinatorRepository.CoordinatorProof( + selectedCommit, List.of(outcome))); + new CommandSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new RealmPolicySourceRepository(f.dsl).captureSynchronized(selectedCommit); + new AssetSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new GameplayRuleSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new TemplateConfigSourceRepository(f.dsl).captureSynchronized(selectedCommit); + coordinator.releaseApplicationSlot(selectedCommit); + + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "ISOLATED retained pre-branding source capture", + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + var selection = + new AuthoredDraftPublishSelectionRepository(f.dsl, coordinator) + .reserve(intent) + .selection(); + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var operation = + IsolatedPublicationOperationFixtures.forSelection(selectionBinding, world); + var attempt = new PublishAttempt(); + attempt.setTenantId(f.target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(f.target.gameDesignVersionRowId()); + attempt.setVersionNumber( + f.dsl + .fetchSingle( + "SELECT version_number FROM version WHERE id = ?", + f.target.gameDesignVersionRowId()) + .get("version_number", Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(f.dsl).save(attempt); + var operations = new GameDesignPublicationOperationRepository(f.dsl); + operations.reserve(operation); + new CommandSourceRepository(f.dsl).freeze(operation); + new RealmPolicySourceRepository(f.dsl).freeze(operation); + new AssetSourceRepository(f.dsl).freeze(operation); + new TemplateConfigSourceRepository(f.dsl).freeze(operation); + var attempts = new PublishAttemptRepository(f.dsl); + var retainedAttempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + retainedAttempt.setStatus(PublishAttemptStatus.FAILED); + retainedAttempt.setFailureCode("ISOLATED_PRE_BRANDING_CAPTURE_HISTORY"); + attempts.save(retainedAttempt); + operations.seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return operation; + })); + } + + private GameDesignPublicationOperation retainFreshV2CaptureWithoutBranding(Fixture f) { + return Objects.requireNonNull( + f.tx.execute( + ignored -> { + try { + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked(f.dsl, f.target, 1); + new CommandSourceRepository(f.dsl).freeze(operation); + new RealmPolicySourceRepository(f.dsl).freeze(operation); + new AssetSourceRepository(f.dsl).freeze(operation); + new GameplayRuleSourceRepository(f.dsl).freeze(operation); + new TemplateConfigSourceRepository(f.dsl).freeze(operation); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + })); + } + + private RetainedCapture retainedCapture(Fixture f, String table, String workflowId) { + var row = + f.dsl.fetchSingle( + "SELECT operation_bytes, capture_bytes, xmin::text AS row_xmin FROM " + + table + + " WHERE publish_workflow_id = ?", + workflowId); + return new RetainedCapture( + row.get("operation_bytes", byte[].class), + row.get("capture_bytes", byte[].class), + row.get("row_xmin", String.class)); + } + + private void assertRetainedCapture( + Fixture f, String table, String workflowId, RetainedCapture original) { + var retained = retainedCapture(f, table, workflowId); + assertThat(retained.operationBytes()).containsExactly(original.operationBytes()); + assertThat(retained.captureBytes()).containsExactly(original.captureBytes()); + assertThat(retained.rowXmin()).isEqualTo(original.rowXmin()); + } + + private record RetainedCapture(byte[] operationBytes, byte[] captureBytes, String rowXmin) {} + private static void insertReviewedBaseV2( DSLContext dsl, DraftCommitBinding binding, GameDesignReviewedBaseEvidence reviewedEvidence) { if (!binding.target().equals(reviewedEvidence.target()) From fdf914f32de33cdfd34952f48460fa7aeea1e997 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:23:28 +1300 Subject: [PATCH 23/36] Author nonempty retained policy while preserving command history proof --- ...BrandingSourcePostgresIntegrationTest.java | 83 +++++++++++-------- 1 file changed, 50 insertions(+), 33 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index 1bd265987f..3a15a79c56 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -3,8 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.nio.charset.StandardCharsets; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -17,8 +17,8 @@ import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; @@ -37,8 +37,8 @@ import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; 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.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -301,7 +301,8 @@ void retainedV2CaptureWithoutBrandingRemainsReadableAsPartialHistory() throws Ex "asset", retainedCapture(f, "game_design_asset_source_capture", operation.workflowId()), "template_config", - retainedCapture(f, "game_design_template_config_source_capture", operation.workflowId())); + retainedCapture( + f, "game_design_template_config_source_capture", operation.workflowId())); var operationBefore = f.dsl.fetchSingle( "SELECT request_bytes, xmin::text AS row_xmin FROM game_design_publication_operation " @@ -336,6 +337,7 @@ void retainedV2CaptureWithoutBrandingRemainsReadableAsPartialHistory() throws Ex var retained = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); assertThat(retained.branding()).isEmpty(); assertThat(retained.gameplay()).isEmpty(); + assertThat(retained.policy().policies()).hasSize(1); assertThat(retained.command().canonicalBytes()) .containsExactly(captureRows.get("command").captureBytes()); assertThat(retained.policy().canonicalBytes()) @@ -355,6 +357,13 @@ void retainedCaptureWithoutBrandingStillFailsForBrandingEnrolledTarget() throws var f = fixture(null); var operation = retainFreshV2CaptureWithoutBranding(f); assertThat(new BrandingSourceRepository(f.dsl).readGenesis(f.target)).isPresent(); + var selectedCommit = operation.account().input().selection().selectedCommit(); + assertThat( + new RealmPolicySourceRepository(f.dsl) + .readSnapshot(f.target, selectedCommit.commitId()) + .orElseThrow() + .policies()) + .hasSize(1); for (String table : List.of( "game_design_command_source_capture", @@ -416,12 +425,19 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { } private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { - var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL")); + var original = + binding( + f, + "0", + CommandSource.SCOPE, + commandUpsert("BRANDING_HISTORICAL"), + policyPayload()); f.tx.executeWithoutResult( ignored -> { var coordinator = new DraftCommitCoordinatorRepository(f.dsl); coordinator.claim(original); - var policyGenesis = new RealmPolicySourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var policyGenesis = + new RealmPolicySourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); var commands = new CommandSourceRepository(f.dsl); var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); var assetGenesis = new AssetSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); @@ -441,29 +457,22 @@ private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { coordinator.claimApplicationSlot(original); coordinator.markOwnerInProgress( original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = commands.apply(original).orElseThrow(); - var out = new java.io.ByteArrayOutputStream(); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, "game-design-control-plane-command-application/v1"); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, original.canonicalBytes()); - net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( - out, applied.canonicalBytes()); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - original.commitId(), - original.digest(), - applied.resultIdentity(), - out.toByteArray(), - List.of(applied.commandAppliedEpoch())); - coordinator.recordOwnerOutcome(original, outcome); + var policies = new RealmPolicySourceRepository(f.dsl); + var command = commands.apply(original).orElseThrow(); + var policy = policies.applyMutation(original); + byte[] siblingEvidence = command.canonicalBytes(); + var appliedEpochs = + List.of( + command.commandAppliedEpoch(), + policy.ownerOutcome().appliedEpochs().getFirst()); + policies.recordCombinedOwnerOutcome(original, siblingEvidence, appliedEpochs); + var outcome = policy.combinedOwnerOutcome(siblingEvidence, appliedEpochs); coordinator.advanceVisibilityFence( original, - new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); + new DraftCommitCoordinatorRepository.CoordinatorProof( + original, List.of(outcome))); commands.captureSynchronized(original); - new RealmPolicySourceRepository(f.dsl).captureSynchronized(original); + policies.captureSynchronized(original); new AssetSourceRepository(f.dsl).captureSynchronized(original); new GameplayRuleSourceRepository(f.dsl).captureSynchronized(original); new TemplateConfigSourceRepository(f.dsl).captureSynchronized(original); @@ -474,8 +483,7 @@ private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { private GameDesignPublicationOperation retainPreBrandingV2Capture( Fixture f, DraftCommitBinding original) throws Exception { - var seed = - IsolatedPublicationOperationFixtures.fresh(f.target, original.commitId().toString()); + var seed = IsolatedPublicationOperationFixtures.fresh(f.target, original.commitId().toString()); var selectedCommit = seed.account().input().selection().selectedCommit(); var world = seed.world(); return Objects.requireNonNull( @@ -485,9 +493,9 @@ private GameDesignPublicationOperation retainPreBrandingV2Capture( var sources = new GameDesignSourceRepository(f.dsl); var originalSources = sources.readSynchronized(f.target, original.commitId()).orElseThrow(); - var originalOutcome = - coordinator.read(f.target, original.requestId()).orElseThrow(); - var reviewed = GameDesignReviewedBaseEvidence.authored(originalSources, originalOutcome); + var originalOutcome = coordinator.read(f.target, original.requestId()).orElseThrow(); + var reviewed = + GameDesignReviewedBaseEvidence.authored(originalSources, originalOutcome); sources.claimReviewed(selectedCommit, reviewed); coordinator.claimApplicationSlot(selectedCommit); coordinator.markOwnerInProgress( @@ -502,7 +510,9 @@ private GameDesignPublicationOperation retainPreBrandingV2Capture( unit.scopeType(), unit.scopeId(), unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + new BigInteger(unit.expectedEpoch()) + .add(BigInteger.ONE) + .toString())) .toList(); var outcome = new DraftCommitCoordinatorRepository.OwnerOutcome( @@ -580,12 +590,19 @@ private GameDesignPublicationOperation retainPreBrandingV2Capture( } private GameDesignPublicationOperation retainFreshV2CaptureWithoutBranding(Fixture f) { + var sourceCommit = binding(f, "0", RealmPolicySource.SCOPE, policyPayload()); + apply(f, sourceCommit); return Objects.requireNonNull( f.tx.execute( ignored -> { try { var operation = - IsolatedPublicationOwnerSetup.retainSourceBacked(f.dsl, f.target, 1); + IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, + f.target, + 1, + "ISOLATED enrolled partial capture without branding", + sourceCommit.commitId().toString()); new CommandSourceRepository(f.dsl).freeze(operation); new RealmPolicySourceRepository(f.dsl).freeze(operation); new AssetSourceRepository(f.dsl).freeze(operation); From 398ebaf756daa084d3b10f7241e11fafb756085e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:26:34 +1300 Subject: [PATCH 24/36] Use owning policy capture accessor in retained branding proof --- ...BrandingSourcePostgresIntegrationTest.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index 3a15a79c56..e7661c3247 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -337,7 +337,7 @@ void retainedV2CaptureWithoutBrandingRemainsReadableAsPartialHistory() throws Ex var retained = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); assertThat(retained.branding()).isEmpty(); assertThat(retained.gameplay()).isEmpty(); - assertThat(retained.policy().policies()).hasSize(1); + assertThat(retained.policy().snapshot().policies()).hasSize(1); assertThat(retained.command().canonicalBytes()) .containsExactly(captureRows.get("command").captureBytes()); assertThat(retained.policy().canonicalBytes()) @@ -426,12 +426,7 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { var original = - binding( - f, - "0", - CommandSource.SCOPE, - commandUpsert("BRANDING_HISTORICAL"), - policyPayload()); + binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL"), policyPayload()); f.tx.executeWithoutResult( ignored -> { var coordinator = new DraftCommitCoordinatorRepository(f.dsl); @@ -463,14 +458,12 @@ private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { byte[] siblingEvidence = command.canonicalBytes(); var appliedEpochs = List.of( - command.commandAppliedEpoch(), - policy.ownerOutcome().appliedEpochs().getFirst()); + command.commandAppliedEpoch(), policy.ownerOutcome().appliedEpochs().getFirst()); policies.recordCombinedOwnerOutcome(original, siblingEvidence, appliedEpochs); var outcome = policy.combinedOwnerOutcome(siblingEvidence, appliedEpochs); coordinator.advanceVisibilityFence( original, - new DraftCommitCoordinatorRepository.CoordinatorProof( - original, List.of(outcome))); + new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); commands.captureSynchronized(original); policies.captureSynchronized(original); new AssetSourceRepository(f.dsl).captureSynchronized(original); @@ -590,7 +583,12 @@ private GameDesignPublicationOperation retainPreBrandingV2Capture( } private GameDesignPublicationOperation retainFreshV2CaptureWithoutBranding(Fixture f) { - var sourceCommit = binding(f, "0", RealmPolicySource.SCOPE, policyPayload()); + var sourceCommit = + binding( + f, + "0", + net.firedevops.firemud.common.gamedesign.RealmPolicySource.SCOPE, + policyPayload()); apply(f, sourceCommit); return Objects.requireNonNull( f.tx.execute( From 2ee09f87e5473ac46bd0bb3edaf1207c5be27517 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 22:21:20 +1300 Subject: [PATCH 25/36] Prove concurrent storage guards and exact owner result bindings --- .../player-access-and-session.md | 6 +- ...rceReservationPostgresIntegrationTest.java | 203 +++++++++++++++++- ...aftSynchronizedVisibilityEvidenceTest.java | 12 +- ...meDesignSourcePostgresIntegrationTest.java | 64 +++++- 4 files changed, 274 insertions(+), 11 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a0036c4f91..fed23a192b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation +This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row. + +Preliminary source reservations remain held until exact explicit abort, including after the creator credential expires; expiry or a lost Game Design response does not establish safe settlement. Exact original recovery and abort remain available after credential expiry, but an abandoned reservation has no Account-owned autonomous recovery path here. Before registering these owners, the selected-recipient finalization and terminal-settlement stage (#3251) must prove Account-owned recovery for abandoned preliminary reservations and exact terminal release for finalized owners. Preserve the complete source fence until sufficient owner evidence exists; do not release it through a guessed timeout. This is an activation blocker, with reconsideration at that lifecycle stage; current source preparation remains unregistered. + The corrected Source-stage R26 gate freshly passes 1,455 Account units with four existing skips and 635 Game Design units with zero skips; Common's 746 units retain R24 attribution. All affected static, formatting and documentation checks pass. R28 freshly passes all eight affected PostgreSQL cases with zero skips: Account V1007 upgrade and current source-exclusion guards, three Branding source and retained-history cases, two stale-Branding first-reference races, and the actual Account-permission-to-Game-Design disclosure composition. The retained V1025 proof uses actual five-family genesis and asset-bound v2 reviewed evidence, preserves historical bytes and row metadata, and acquires no Branding lineage through upgrade. Full-native qualification remains held: R26 Account executes 291 cases with three failures, Game Design 162 with five failures, and Game Design cross-service 26 with two failures, all with zero skips. Eight fixture failures are corrected by the focused proof; the inherited PostgreSQL host-port refusal and Redis host-port startup timeout remain unresolved. No production authority, absent-family fallback, schema or readiness-policy change is introduced. The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, and passes in R28. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition passes with controlled upstream inputs; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. @@ -216,7 +220,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The standalone Account acquisition/read/settlement owners and World protected-activation consumer are now available as unregistered source. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The standalone Account acquisition/read/settlement owners and World protected-activation consumer are now available as unregistered source. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index 03c2041e73..fd098f481b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -4,21 +4,28 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionTemplate; /** PostgreSQL installation proof for V1007's additive selected-owner source reservations. */ class AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest { @Test - void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWithoutSourceRows() - throws Exception { + void installsV1007AndRejectsMalformedAndDeferredIncompleteReservations() throws Exception { var fixture = new AccountPostgresIntegrationFixture(); try (AutoCloseable fixtureCleanup = fixture::stop) { fixture.start(); @@ -124,6 +131,8 @@ void installsV1007OverCombinedV1006ParentGuardsAndRejectsMalformedReservationWit "account_selected_owner_intake_source_read_sources source", "Pending selected owner intake source read excludes hosted-terms dispatch"); + assertDeferredCompletenessTriggerRejectsWrongScopeDigest( + jdbc, ownerTransaction, savedAccount.getAccountUuid()); assertMalformedReservationCreatesNoSourceRows(jdbc); assertThat(retainedParentRows(jdbc)).isEqualTo(retainedParent); } @@ -262,6 +271,196 @@ private static void assertMalformedReservationCreatesNoSourceRows(JdbcTemplate j assertThat(count(jdbc, "account_selected_owner_intake_source_read_aborts")).isZero(); } + private static void assertDeferredCompletenessTriggerRejectsWrongScopeDigest( + JdbcTemplate jdbc, TransactionTemplate transaction, UUID actorAccountUuid) { + // The persisted creator fixture follows Account's existing fresh-tenant/issuance row shape. + UUID tenantUuid = UUID.randomUUID(); + jdbc.update( + "INSERT INTO account_fresh_tenant_identity_associations (" + + "schema_version, target_namespace, creation_request_id, operation_id, " + + "request_digest, canonical_tenant_id, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (1, 'test-owner', ?, ?, ?, ?, 1, ?, " + + "'NEW_GAME_ROW', ?)", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + tenantUuid, + tenantUuid.toString(), + "sha256:" + "b".repeat(64)); + + UUID intakeRequestId = UUID.randomUUID(); + UUID versionUuid = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenantUuid, + versionUuid, + 1, + tenantUuid.toString(), + 1, + tenantUuid.toString(), + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "fixture-base-commit", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test-only selected entity revision")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "entity", + "fixture-entity", + "tenant", + tenantUuid.toString(), + "1"))); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test-owner", + operationId, + fenceId, + intakeRequestId, + actorAccountUuid, + selected); + + UUID issuanceOperationId = UUID.randomUUID(); + String sourcePayloadJson = + "{\"accountId\":\"" + + actorAccountUuid + + "\",\"schemaVersion\":1,\"sources\":[],\"tenantId\":\"" + + tenantUuid + + "\"}"; + String issuanceBundleJson = "{\"issuanceFence\":1,\"outboxCheckpoints\":[]}"; + byte[] sourcePayload = sourcePayloadJson.getBytes(StandardCharsets.UTF_8); + byte[] issuanceBundle = issuanceBundleJson.getBytes(StandardCharsets.UTF_8); + byte[] outboxCheckpoints = "[]".getBytes(StandardCharsets.UTF_8); + long issuedAtEpochSecond = Instant.now().getEpochSecond(); + long expiresAtEpochSecond = issuedAtEpochSecond + 300; + OffsetDateTime recoveryExpiresAt = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAtEpochSecond + 60), ZoneOffset.UTC); + jdbc.update( + "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, registry_cleanup_deadline_epoch_millis, " + + "recovery_expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?::timestamptz, 'PREPARED')", + UUID.randomUUID(), + issuanceOperationId, + UUID.randomUUID(), + actorAccountUuid, + tenantUuid, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "test-fixture", + "c".repeat(64), + ("{\"accountId\":\"" + actorAccountUuid + "\"}").getBytes(StandardCharsets.UTF_8), + sourcePayload, + issuanceBundle, + "test-only issuer fixture receipt".getBytes(StandardCharsets.UTF_8), + issuedAtEpochSecond, + expiresAtEpochSecond, + (expiresAtEpochSecond + 300) * 1000, + recoveryExpiresAt); + jdbc.update( + "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " + + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", + "d".repeat(64), + "test-only pending registry".getBytes(StandardCharsets.UTF_8), + "test-only active registry".getBytes(StandardCharsets.UTF_8), + issuanceOperationId); + jdbc.update( + "INSERT INTO account_control_ui_response_envelopes (" + + "operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?::timestamptz)", + issuanceOperationId, + "test-only protected response".getBytes(StandardCharsets.UTF_8), + "test-only response binding".getBytes(StandardCharsets.UTF_8), + recoveryExpiresAt); + jdbc.update( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + "test-only committed issuer receipt".getBytes(StandardCharsets.UTF_8), + issuanceOperationId); + + Map existingRows = ownerReservationRowCounts(jdbc); + String correctScopeDigest = scope.digest(); + char lastHex = correctScopeDigest.charAt(correctScopeDigest.length() - 1); + String wrongScopeDigest = + correctScopeDigest.substring(0, correctScopeDigest.length() - 1) + + (lastHex == '0' ? '1' : '0'); + assertThat(wrongScopeDigest).matches("^sha256:[0-9a-f]{64}$").isNotEqualTo(correctScopeDigest); + + int[] insertedRows = {0}; + assertThatThrownBy( + () -> + transaction.execute( + status -> { + insertedRows[0] = + jdbc.update( + "INSERT INTO account_selected_owner_intake_source_read_reservations (" + + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "1, ?, ?, ?)", + operationId, + fenceId, + intakeRequestId, + scope.owner().name(), + actorAccountUuid, + tenantUuid, + versionUuid, + scope.canonicalBytes(), + wrongScopeDigest, + issuanceOperationId, + sourcePayload, + issuanceBundle, + outboxCheckpoints); + return null; + })) + .satisfies( + failure -> { + PSQLException postgresFailure = postgresException(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getServerErrorMessage().getMessage()) + .isEqualTo( + "Preliminary owner scope requires exact current committed creator evidence"); + }); + + assertThat(insertedRows[0]).isEqualTo(1); + assertThat(ownerReservationRowCounts(jdbc)).isEqualTo(existingRows); + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM account_selected_owner_intake_source_read_reservations " + + "WHERE operation_id = ?", + Integer.class, + operationId))) + .isZero(); + } + + private static Map ownerReservationRowCounts(JdbcTemplate jdbc) { + return Map.of( + "reservations", count(jdbc, "account_selected_owner_intake_source_read_reservations"), + "sources", count(jdbc, "account_selected_owner_intake_source_read_sources"), + "aborts", count(jdbc, "account_selected_owner_intake_source_read_aborts")); + } + + private static PSQLException postgresException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof PSQLException postgresFailure) return postgresFailure; + } + throw new AssertionError("Expected PostgreSQL deferred-constraint failure", failure); + } + private static void assertWorldSourceExclusionGuards( String holdGuard, String sourceChangeGuard, String disclosureGuard) { assertThat(holdGuard) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java index 2d088881f1..be18b8f2df 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java @@ -59,7 +59,7 @@ void requiresExactlyOneAppliedEpochAdvanceAcrossLargeCounters() throws Exception } @Test - void completeAllOwnerFenceValidatesAndReturnsDefensiveExactWorldResult() { + void completeAllOwnerFenceValidatesAndReturnsDefensiveExactOwnerResults() { var evidence = evidence(multiOwnerBinding(), resultVector(multiOwnerBinding())); evidence.requireValid(); @@ -70,6 +70,12 @@ void completeAllOwnerFenceValidatesAndReturnsDefensiveExactWorldResult() { resultBytes[0] = 0; assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultBytes()) .containsExactly("world-result-bytes".getBytes(StandardCharsets.UTF_8)); + assertThat(evidence.appliedOwnerResult(Owner.ENTITY_MANAGEMENT).resultIdentity()) + .isEqualTo("entity-result"); + byte[] entityBytes = evidence.appliedOwnerResult(Owner.ENTITY_MANAGEMENT).resultBytes(); + entityBytes[0] = 0; + assertThat(evidence.appliedOwnerResult(Owner.ENTITY_MANAGEMENT).resultBytes()) + .containsExactly("entity-result-bytes".getBytes(StandardCharsets.UTF_8)); } @Test @@ -256,7 +262,9 @@ private static String resultVector(DraftCommitBinding binding) { item.put( "resultBytesBase64", Base64.getEncoder() - .encodeToString("world-result-bytes".getBytes(StandardCharsets.UTF_8))); + .encodeToString( + (owner == Owner.WORLD_MANAGEMENT ? "world-result-bytes" : "entity-result-bytes") + .getBytes(StandardCharsets.UTF_8))); item.put("appliedEpochs", List.of(epoch)); vector.add(item); } 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 f434dca060..935c9fc284 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 @@ -1789,19 +1789,25 @@ void rawLifecycleFirstRejectsSlotInsertAcrossSupportedIsolationLevels() throws E var slotSql = DSL.using(slot, SQLDialect.POSTGRES); slotSql.fetch( "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); - DSL.using(lifecycle, SQLDialect.POSTGRES) - .execute( - "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", - local.target().gameDesignVersionRowId()); + var lifecycleSql = DSL.using(lifecycle, SQLDialect.POSTGRES); + lifecycleSql.execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target().gameDesignVersionRowId()); + int lifecyclePid = storageBackendPid(lifecycleSql); var started = new java.util.concurrent.CountDownLatch(1); + var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = worker.submit( () -> { + workerPid.set(storageBackendPid(slotSql)); started.countDown(); return failedStorageWrite(() -> insertRawSlot(slotSql, binding)); }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(awaitStorageBackendBlock(local, lifecyclePid, workerPid.get())) + .as("slot writer backend blocked by lifecycle backend") + .isTrue(); } finally { lifecycle.commit(); } @@ -1838,11 +1844,14 @@ void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVers var lifecycleSql = DSL.using(lifecycle, SQLDialect.POSTGRES); lifecycleSql.fetch( "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); + int slotPid = storageBackendPid(DSL.using(slot, SQLDialect.POSTGRES)); insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), binding); var started = new java.util.concurrent.CountDownLatch(1); + var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var updating = worker.submit( () -> { + workerPid.set(storageBackendPid(lifecycleSql)); started.countDown(); return failedStorageWrite( () -> @@ -1852,6 +1861,9 @@ void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVers }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) + .as("lifecycle writer backend blocked by slot backend") + .isTrue(); } finally { slot.commit(); } @@ -1881,16 +1893,23 @@ void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() t var slotSql = DSL.using(slot, SQLDialect.POSTGRES); slotSql.fetch( "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); - insertRawSelection(DSL.using(selection, SQLDialect.POSTGRES), selected); + var selectionSql = DSL.using(selection, SQLDialect.POSTGRES); + int selectionPid = storageBackendPid(selectionSql); + insertRawSelection(selectionSql, selected); var started = new java.util.concurrent.CountDownLatch(1); + var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = worker.submit( () -> { + workerPid.set(storageBackendPid(slotSql)); started.countDown(); return failedStorageWrite(() -> insertRawSlot(slotSql, later)); }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(awaitStorageBackendBlock(local, selectionPid, workerPid.get())) + .as("slot writer backend blocked by selection backend") + .isTrue(); } finally { selection.commit(); } @@ -1920,19 +1939,26 @@ void rawSlotFirstRejectsSelectionEvenWhenSelectionSnapshotPredatesSlot() throws try (var slot = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); var selection = storageConnection(local, isolation); var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var slotSql = DSL.using(slot, SQLDialect.POSTGRES); + int slotPid = storageBackendPid(slotSql); var selectionSql = DSL.using(selection, SQLDialect.POSTGRES); selectionSql.fetch( "SELECT * FROM version WHERE id = ?", local.target().gameDesignVersionRowId()); - insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), later); + insertRawSlot(slotSql, later); var started = new java.util.concurrent.CountDownLatch(1); + var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = worker.submit( () -> { + workerPid.set(storageBackendPid(selectionSql)); started.countDown(); return failedStorageWrite(() -> insertRawSelection(selectionSql, selected)); }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) + .as("selection writer backend blocked by slot backend") + .isTrue(); } finally { slot.commit(); } @@ -1959,6 +1985,32 @@ private int[] storageIsolationLevels() { }; } + private int storageBackendPid(DSLContext sql) { + return Objects.requireNonNull( + sql.fetchOne("SELECT pg_backend_pid()"), "storage transaction must expose its backend") + .get(0, Integer.class); + } + + private boolean awaitStorageBackendBlock(Fixture local, int firstPid, int workerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var activity = + local + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + firstPid, + workerPid); + if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { + return true; + } + Thread.sleep(25); + } + return false; + } + private Connection storageConnection(Fixture local, int isolation) throws SQLException { var connection = DriverManager.getConnection( From abb901526b9494d7f20b38fbb22f7899acf757c8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:05:22 +1300 Subject: [PATCH 26/36] Append new observations after existing entries --- design/project-management/ai-observations.md | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5d79c94567..be824937db 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -115,32 +115,12 @@ Entry format: - Expected pattern: Compare every patch target with the pinned worktree path, then inspect the first written file at that absolute destination before continuing. This destination check remains manual. - Reconsideration trigger: enforce destination verification at the native patch boundary, or repeat measurement disproves the risk; completion of migration review alone does not resolve it. -- `2026-10-15`: Allocate forward migrations against the resolved combined Flyway history - - Context: The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history, including shared Saga resources and later service-owned migrations. - - Observation: The receiving Account parent already reaches V1005, while Saga reaches V1002. - - Expected pattern: Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. - -- `2026-10-16`: Use bounded admission for shared heavy runs - - Context: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. - - Observation: A Document source gate automatically acquired the lock before its delayed peer completion message arrived. - - Expected pattern: Treat busy admission as unrun proof. - -- `2026-10-16`: Bound conflict markers and inspect reconstructed files - - Context: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. - - Observation: Native `git merge-file` reconstruction from the exact parents recovered the complete files; a clean whitespace check alone cannot detect lost content. - - Expected pattern: Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing. - - `2026-10-15`: Preserve receiver status when relocating inherited tracker proof - Context: the local #3224 parent reconciliation relocated inherited LOGIN proof into a dedicated section. Selecting the complete incoming tracker plus one receiver proof paragraph also displaced the receiver's first-party denial and historical-proof qualifications. The candidate had not been published. - Observation: verifying nonoverlapping blobs and paragraphs unique against the merge base missed receiver status that also appeared in the base. Main later compared the complete receiver document, restored every original receiver paragraph byte-for-byte, and retained the incoming concise status and relocated proof. No production source changed. - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. -- `2026-10-16`: Check both public mapping directions for transport identity - - Context: An internal read requires an identity distinct from its original operation. The launch-association receiver retained the guard while a refactor removed it from the request encoder. - - Observation: The receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. - - Expected pattern: Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. - - `2026-10-16`: Report source validation separately from packaged smoke - Context: PR #3224 had a successful Validation result and a separate runtime-image Smoke failure in run [38844094461](https://github.com/benhook1013/FireMUD/actions/runs/38844094461); the retained local job record showed Gateway and TCP Proxy public readiness intentionally out of service after the bounded Compose wait. - Observation: successful source validation does not replace packaged-image runtime proof, and an expected held-readiness result does not justify weakening public readiness or extending timeouts. @@ -219,14 +199,34 @@ Entry format: - 2026-10-18: CodeRabbit full review 5560170943 for PR #3264 emitted a complete 1/1 publication with one outside-diff Major but no bounded actionable-comment count. The existing manual adoption correctly refused automatic attribution with `Hosted publication has no unique bounded actionable-comment count`. Exact trigger 6241278398, reviewed head `187ab53426caf78cd6a01b61e092b800186aaec2`, provider result and accepted obligation were retained in the CI validation throughput controller job history without invented Hosted credit; no controller adapter change was made in this CI patch. Reconsider format support only in a separately scoped controller maintenance task. -- `2026-10-18`: Keep automatic Git repack failures separate from local commit proof - - Context: The #3248 private-parent receiving commit `029b6299b0ec63a6cd0a1cd30197cc7b3ca56ded` triggered automatic Git maintenance in the shared repository. - - Observation: The commit succeeded, and background repack reported `fatal: bad object refs/remotes/origin/codex/document-original-world-preparation-20261015` and `fatal: failed to run repack`. The exact cause and repository object health remain unknown. - - Expected pattern: Record commit and receiving evidence separately from background maintenance results. Investigate only under qualified shared-repository maintenance or when an actual delivery blocker requires it; `gc.log` or unreachable-object warnings do not authorize cleanup. - - Status and reconsideration: The commit retained prospective tree `733ed58d9390a5ba00e24088435af7b847567527`, all 84 child-owned postimages and the deletion, and all 12 qualified incoming blobs. Evidence is in Controller current-gameplay update 2151, `private-parent-carry-via-09e-verification.json`, and `receive-qualified-private-cli1-parent.patch` under the private #3248 local current-parent-carry evidence. Revisit if a qualified maintenance pass identifies the cause or the failure blocks delivery. - - `2026-10-18`: PR retarget can fail exact merge-parent metadata checks - Context: After #3237 merged and #3246 was retargeted to `develop`, Runtime Images run `39093729815` and Preview run `39093729854` checked the retargeted head/base pair. - Observation: Both runs rejected the selected test-merge commit because it did not have its exact parents. Runtime failed before image production; Preview exhausted five merge-computation attempts. The PR Runtime path uses `GITHUB_SHA`; an empty dispatch-only `EVENT_MERGE_SHA` is not the cause. The reason for the mismatched merge selection is unconfirmed. - Expected pattern: The previous parent's green runs do not qualify the new pair. Preserve the exact-parent guard and do not rerun blindly. No guard was weakened and no blind rerun was requested. - Recovery: Gameplay reported the captured failures to Overseer in controller message `64512c73-9fa2-44b5-b2b7-e5b607155777`, with Preview evidence in reply `0de28b96-8790-4e5e-b8e5-a915d96de829`. After normal parent reconciliation and the required correction push to `a9d9f27a4139c2be2cbf9b7c1df4c4a33d6b8bf3` on `develop` at `efbc55874894ce5b2b420e19fac5ab23d66e384e`, replacement Runtime Images run `39094799761` and Preview run `39094798308` both succeeded. This establishes recovery of those metadata checks after that publication boundary, without explaining the original mismatch or claiming whole-CI success. + +- `2026-10-15`: Allocate forward migrations against the resolved combined Flyway history + - Context: The selected-owner intake plan's older Account V161 and Automation V5 sketch would sort below already installed combined history, including shared Saga resources and later service-owned migrations. + - Observation: The receiving Account parent already reaches V1005, while Saga reaches V1002. + - Expected pattern: Preserve existing SQL and prove a retained upgrade from the actual combined parent instead of enabling out-of-order execution or inferring a frontier from the service's older application lineage. + +- `2026-10-16`: Use bounded admission for shared heavy runs + - Context: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. + - Observation: A Document source gate automatically acquired the lock before its delayed peer completion message arrived. + - Expected pattern: Treat busy admission as unrun proof. + +- `2026-10-16`: Bound conflict markers and inspect reconstructed files + - Context: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. + - Observation: Native `git merge-file` reconstruction from the exact parents recovered the complete files; a clean whitespace check alone cannot detect lost content. + - Expected pattern: Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing. + +- `2026-10-16`: Check both public mapping directions for transport identity + - Context: An internal read requires an identity distinct from its original operation. The launch-association receiver retained the guard while a refactor removed it from the request encoder. + - Observation: The receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. + - Expected pattern: Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. + +- `2026-10-18`: Keep automatic Git repack failures separate from local commit proof + - Context: The #3248 private-parent receiving commit `029b6299b0ec63a6cd0a1cd30197cc7b3ca56ded` triggered automatic Git maintenance in the shared repository. + - Observation: The commit succeeded, and background repack reported `fatal: bad object refs/remotes/origin/codex/document-original-world-preparation-20261015` and `fatal: failed to run repack`. The exact cause and repository object health remain unknown. + - Expected pattern: Record commit and receiving evidence separately from background maintenance results. Investigate only under qualified shared-repository maintenance or when an actual delivery blocker requires it; `gc.log` or unreachable-object warnings do not authorize cleanup. + - Status and reconsideration: The commit retained prospective tree `733ed58d9390a5ba00e24088435af7b847567527`, all 84 child-owned postimages and the deletion, and all 12 qualified incoming blobs. Evidence is in Controller current-gameplay update 2151, `private-parent-carry-via-09e-verification.json`, and `receive-qualified-private-cli1-parent.patch` under the private #3248 local current-parent-carry evidence. Revisit if a qualified maintenance pass identifies the cause or the failure blocks delivery. From 12344563b1276e431b867fd76daee03c526807be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:20:37 +1300 Subject: [PATCH 27/36] Make retained Draft branding publication restrictions explicit --- .../game-authoring-publishing-and-activation.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index e8144f7cfb..46d26224a8 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 @@ -114,6 +114,10 @@ The existing gameplay-rule owner now prepares an immutable capture of the origin This earliest owner stage composes command, policy, ordinary asset and gameplay capture. Later template and branding owners retain their separate placement; complete six-family consumer equality must be qualified after propagation. On source `2219bf43e47afd3c55889466927db5f29a94daab`, the whole Game Design gate freshly passed 564 units, 24 cross-service cases and 139 of 140 native cases; the sole failure was the new historical fixture sealing an operation before marking its attempt failed. After correcting that fixture through the existing owner repository, all sixteen source-owner native cases freshly passed on `8fc62a51963b681682d887d28a7d5af803c7b22f` (2026-10-16 10:00:00–10:00:43 UTC), including exact empty and nonempty capture, immutable retry, generic and legacy source refusal, retained predecessor bytes and row versions, and refusal to extend terminal history. Static and formatting checks passed; the focused run reused their up-to-date results. Main verified the fresh saved XML and exact test PostgreSQL absence. The earlier whole gate retains its failed attribution; no whole-service success is claimed for it. This source adds no registered publication ingress, genuine creator or owner authority, activation, admission or completed Gameplay handoff. +#### Retained Draft branding publication boundary + +Retained Versions without branding genesis remain historical-only: the [canonical six-family publication contract](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations) says missing capture is unknown and retained pre-feature evidence cannot authorize fresh publication. `BrandingSourceRepository.enrollFreshDraft` requires a same-transaction fresh insertion, while `GameDesignSourceRepository` requires branding genesis for fresh `apply`, `captureSynchronized` and `freeze`; no repair or re-enrollment mechanism is established. The retained-history proof in [BrandingSourcePostgresIntegrationTest](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java) confirms the old five-family rows and bytes remain unchanged, historical branding reads empty, and genesis, capture and enrollment are refused; a separate case preserves historical V2 capture as partial history. Any future enablement requires a canonical new owner-evidenced path. + ### Account terminal-settlement continuation The prepared continuation adds unregistered Account reconciliation and exact Game Design/World terminal-read adapters. Account reads missing required-owner evidence outside its transactions, rechecks the immutable original binding and ordering, retains exact readbacks through the existing repository, and derives settlement through that repository's complete-owner predicate. Unsupported required v2 participants stay pending. World preserves current APPLIED graph and inbound-closure decoding and uses the inherited definitive-abort owner history; Game Design reads its existing durable terminal owner. No migration, service registration, source authority, publication or runtime permission is added. From 40d70d71ff3a30f61b1d7197c66bd5603b87b5d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:06:00 +1300 Subject: [PATCH 28/36] docs(account): align selected source reservation implementation status --- .../microservices/account-service/runtime-and-data.md | 2 +- .../microservices/game-design-service/version-control.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 71aef27647..0c5dddb7f6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -354,4 +354,4 @@ Forward [V1004.2](../../../../services/account-service/src/main/resources/db/mig Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). -V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. +V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) now provides preliminary selected-owner reservation and source-writer storage; finalized owner authorization and recovery, exact terminal settlement, full qualification and registration remain unproved. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 4af6f476be..602bd309c5 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,7 +6,7 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status -The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing V1007 storage, and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). +The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing [Game Design V1007 branding-source storage](../../../../services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql), and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). The shared strict selected-full attestation and terminal codecs, read-only World lifecycle support for schema 4 and a class-only guarded World evidence fixture are source-prepared and unqualified in this read stage. The actual Game Design writer/storage integration, fixture factory execution and five-store owner composition remain in the full selected-owner successor; this preparation supplies no fresh publication authority. Public fresh/PENDING publication remains denied and no activation or component registration is enabled. Current execution attribution and remaining qualification are recorded in the [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index fed23a192b..92a4edaca8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -66,7 +66,7 @@ Focused proof is split by unchanged source attribution: twelve shared validator ### Original StartSession source-protection storage -The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. +The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. Finalized owner authorization and recovery, exact terminal settlement, full qualification, and registration remain separate unfinished dependencies. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). From bd1b8d11ee5f09db41f637782facf02365d3bbc4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 07:09:57 +1300 Subject: [PATCH 29/36] Prove exact selected-source reservation digest rejection --- .../V1007__selected_owner_intake_source_reservations.sql | 7 +++++-- ...wnerIntakeSourceReservationPostgresIntegrationTest.java | 3 +-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql b/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql index c6764eb66c..72f9d61fc9 100644 --- a/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql +++ b/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql @@ -84,11 +84,14 @@ BEGIN OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' - IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB - OR NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB THEN RAISE EXCEPTION 'Preliminary owner scope requires exact current committed creator evidence' USING ERRCODE = '23514'; END IF; + IF NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Preliminary owner scope digest does not match canonical bytes' + USING ERRCODE = '23514'; + END IF; SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index fd098f481b..b4cf678e7c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -431,8 +431,7 @@ private static void assertDeferredCompletenessTriggerRejectsWrongScopeDigest( PSQLException postgresFailure = postgresException(failure); assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); assertThat(postgresFailure.getServerErrorMessage().getMessage()) - .isEqualTo( - "Preliminary owner scope requires exact current committed creator evidence"); + .isEqualTo("Preliminary owner scope digest does not match canonical bytes"); }); assertThat(insertedRows[0]).isEqualTo(1); From d74177ff202fbb2fb915a98bdc7c81fa23c833a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:18:18 +1300 Subject: [PATCH 30/36] test: await mapped PostgreSQL JDBC readiness before migrations --- ...ntialCleanupRepositoryIntegrationTest.java | 2 + .../PostgresBackedServiceTestSupport.java | 53 +++++++++++++++++++ ...teConfigSourcePostgresIntegrationTest.java | 7 +++ .../GameDesignPostgresIntegrationFixture.java | 2 + ...leaseCanonicalIdentityIntegrationTest.java | 7 +++ 5 files changed, 71 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java index 4fa2bcedaa..3f26d685aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import javax.sql.DataSource; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -51,6 +52,7 @@ class CredentialCleanupRepositoryIntegrationTest { @BeforeAll void setUpRepositories() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); DriverManagerDataSource source = newDataSource(); dataSource = source; Flyway.configure() diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java index 25a6f31d71..0a6a4cd06e 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java @@ -2,7 +2,17 @@ import java.nio.file.Files; import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; import java.util.Map; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; +import org.awaitility.Awaitility; +import org.awaitility.core.ConditionTimeoutException; import org.springframework.test.context.DynamicPropertyRegistry; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -33,6 +43,49 @@ public static DockerImageName postgresImage(String imageReference) { return image.asCompatibleSubstituteFor(DockerImageName.parse("postgres")); } + public static void awaitPostgresJdbcReady(PostgreSQLContainer postgres) { + String jdbcUrl = postgres.getJdbcUrl(); + Properties connectionProperties = new Properties(); + connectionProperties.setProperty("user", postgres.getUsername()); + connectionProperties.setProperty("password", postgres.getPassword()); + connectionProperties.setProperty("connectTimeout", "2"); + connectionProperties.setProperty("socketTimeout", "2"); + AtomicReference lastFailure = new AtomicReference<>(); + + try { + Awaitility.await() + .alias("PostgreSQL mapped JDBC readiness at " + jdbcUrl) + .pollInterval(Duration.ofMillis(100)) + .atMost(Duration.ofSeconds(60)) + .until( + () -> { + try (Connection connection = + DriverManager.getConnection(jdbcUrl, connectionProperties); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SELECT 1")) { + if (result.next() && result.getInt(1) == 1) { + return true; + } + lastFailure.set(new SQLException("PostgreSQL readiness query did not return 1")); + return false; + } catch (SQLException failure) { + lastFailure.set(failure); + return false; + } + }); + } catch (ConditionTimeoutException timeout) { + SQLException failure = lastFailure.get(); + if (failure == null) { + throw timeout; + } + IllegalStateException readinessFailure = + new IllegalStateException( + "Timed out waiting for PostgreSQL mapped JDBC readiness", failure); + readinessFailure.addSuppressed(timeout); + throw readinessFailure; + } + } + public static void registerPostgresService( DynamicPropertyRegistry registry, PostgreSQLContainer postgres, String serviceSchema) { String flywayLocations = filesystemFlywayLocations(serviceSchema); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index be507d77b9..76f8099586 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -41,12 +41,14 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +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.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -67,6 +69,11 @@ class TemplateConfigSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + } + @Test void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvenance() { var f = fixture(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameDesignPostgresIntegrationFixture.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameDesignPostgresIntegrationFixture.java index 7f41eeac50..2a06c2c4f7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameDesignPostgresIntegrationFixture.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameDesignPostgresIntegrationFixture.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.util.Properties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; @@ -23,6 +24,7 @@ void start() { "Docker is unavailable; the PostgreSQL test fixture requires Testcontainers"); container.start(); started = true; + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(container); } void stop() { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 5db106da16..56104b7ac5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -24,6 +25,7 @@ import org.jooq.impl.DSL; import org.jooq.impl.DataSourceConnectionProvider; import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -59,6 +61,11 @@ class PublishedReleaseCanonicalIdentityIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { Fixture fixture = fixture(null); From e7b17e9a1aa2e2cdf4af17c2498303f778a51091 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:37:16 +1300 Subject: [PATCH 31/36] test: retain PostgreSQL state when JDBC readiness times out --- .../PostgresBackedServiceTestSupport.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java index 0a6a4cd06e..ce1a4be489 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.test; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.NetworkSettings; +import com.github.dockerjava.api.model.Ports; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; @@ -19,6 +24,8 @@ import org.testcontainers.utility.DockerImageName; public final class PostgresBackedServiceTestSupport { + private static final int POSTGRES_PORT = 5432; + private static final int MAX_DIAGNOSTIC_LOG_BYTES = 16 * 1024; private static final Map SERVICE_MODULE_DIRECTORY = Map.ofEntries( Map.entry("account_service", "account-service"), @@ -76,16 +83,94 @@ public static void awaitPostgresJdbcReady(PostgreSQLContainer postgres) { } catch (ConditionTimeoutException timeout) { SQLException failure = lastFailure.get(); if (failure == null) { + attachPostgresReadinessDiagnostics(postgres, timeout); throw timeout; } IllegalStateException readinessFailure = new IllegalStateException( "Timed out waiting for PostgreSQL mapped JDBC readiness", failure); readinessFailure.addSuppressed(timeout); + attachPostgresReadinessDiagnostics(postgres, readinessFailure); throw readinessFailure; } } + private static void attachPostgresReadinessDiagnostics( + PostgreSQLContainer postgres, Throwable readinessFailure) { + try { + String diagnostics = capturePostgresReadinessDiagnostics(postgres); + readinessFailure.addSuppressed(new IllegalStateException(diagnostics)); + System.err.println(diagnostics); + } catch (RuntimeException diagnosticsFailure) { + readinessFailure.addSuppressed( + new IllegalStateException( + "PostgreSQL readiness diagnostic collection failed", diagnosticsFailure)); + } + } + + private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer postgres) { + String containerId = postgres.getContainerId(); + String host = postgres.getHost(); + Integer mappedPort = postgres.getMappedPort(POSTGRES_PORT); + InspectContainerResponse containerInfo = postgres.getCurrentContainerInfo(); + InspectContainerResponse.ContainerState state = containerInfo.getState(); + String logs = tailUtf8(postgres.getLogs(), MAX_DIAGNOSTIC_LOG_BYTES); + + return "PostgreSQL JDBC readiness timeout diagnostics:" + + "\ncontainerId=" + + containerId + + "\nhost=" + + host + + "\nmappedPort=" + + mappedPort + + "\nstate.running=" + + (state == null ? null : state.getRunning()) + + "\nstate.oomKilled=" + + (state == null ? null : state.getOOMKilled()) + + "\nstate.exitCode=" + + (state == null ? null : state.getExitCodeLong()) + + "\nstate.error=" + + (state == null ? null : state.getError()) + + "\nmappedPortBindings[5432/tcp]=" + + postgresPortBindings(containerInfo) + + "\npostgresStartupLogTail(maxBytes=" + + MAX_DIAGNOSTIC_LOG_BYTES + + "):\n" + + logs; + } + + private static String postgresPortBindings(InspectContainerResponse containerInfo) { + NetworkSettings networkSettings = containerInfo.getNetworkSettings(); + Ports ports = networkSettings == null ? null : networkSettings.getPorts(); + Ports.Binding[] bindings = + ports == null ? null : ports.getBindings().get(ExposedPort.tcp(POSTGRES_PORT)); + if (bindings == null || bindings.length == 0) { + return ""; + } + + StringBuilder result = new StringBuilder(); + for (Ports.Binding binding : bindings) { + if (result.length() > 0) { + result.append(','); + } + result.append(binding.getHostIp()).append(':').append(binding.getHostPortSpec()); + } + return result.toString(); + } + + private static String tailUtf8(String value, int maxBytes) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + if (bytes.length <= maxBytes) { + return value; + } + + int start = bytes.length - maxBytes; + while (start < bytes.length && (bytes[start] & 0xc0) == 0x80) { + start++; + } + return new String(bytes, start, bytes.length - start, StandardCharsets.UTF_8); + } + public static void registerPostgresService( DynamicPropertyRegistry registry, PostgreSQLContainer postgres, String serviceSchema) { String flywayLocations = filesystemFlywayLocations(serviceSchema); From 3237d1d8126207750871a53f56622efc0daf15e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:17:49 +1300 Subject: [PATCH 32/36] Capture JVM address resolution after PostgreSQL readiness timeout --- .../PostgresBackedServiceTestSupport.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java index ce1a4be489..988182b73f 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java @@ -4,6 +4,8 @@ import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.NetworkSettings; import com.github.dockerjava.api.model.Ports; +import java.net.InetAddress; +import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -112,6 +114,7 @@ private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer String containerId = postgres.getContainerId(); String host = postgres.getHost(); Integer mappedPort = postgres.getMappedPort(POSTGRES_PORT); + String resolvedHostAddresses = resolvedHostAddresses(host); InspectContainerResponse containerInfo = postgres.getCurrentContainerInfo(); InspectContainerResponse.ContainerState state = containerInfo.getState(); String logs = tailUtf8(postgres.getLogs(), MAX_DIAGNOSTIC_LOG_BYTES); @@ -121,6 +124,12 @@ private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer + containerId + "\nhost=" + host + + "\nresolvedHostAddresses=" + + resolvedHostAddresses + + "\njava.net.preferIPv4Stack=" + + jvmPreference("java.net.preferIPv4Stack") + + "\njava.net.preferIPv6Addresses=" + + jvmPreference("java.net.preferIPv6Addresses") + "\nmappedPort=" + mappedPort + "\nstate.running=" @@ -139,6 +148,37 @@ private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer + logs; } + private static String resolvedHostAddresses(String host) { + try { + InetAddress[] addresses = InetAddress.getAllByName(host); + StringBuilder result = new StringBuilder(); + int count = Math.min(addresses.length, 8); + for (int index = 0; index < count; index++) { + if (result.length() > 0) { + result.append(','); + } + result.append(addresses[index].getHostAddress()); + } + if (addresses.length > count) { + result.append(",...(truncated)"); + } + return result.toString(); + } catch (UnknownHostException failure) { + return ""; + } + } + + private static String jvmPreference(String name) { + String value = System.getProperty(name); + if (value == null) { + return ""; + } + if (value.equals("true") || value.equals("false") || value.equals("system")) { + return value; + } + return ""; + } + private static String postgresPortBindings(InspectContainerResponse containerInfo) { NetworkSettings networkSettings = containerInfo.getNetworkSettings(); Ports ports = networkSettings == null ? null : networkSettings.getPorts(); From faabb1f58e7b5d05e832fd1d56c8e8f4fcd77dd7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:03:17 +1300 Subject: [PATCH 33/36] Collect internal PostgreSQL health after mapped-port timeout --- .../PostgresBackedServiceTestSupport.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java index 988182b73f..346bc15202 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.NetworkSettings; import com.github.dockerjava.api.model.Ports; +import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; @@ -118,6 +119,7 @@ private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer InspectContainerResponse containerInfo = postgres.getCurrentContainerInfo(); InspectContainerResponse.ContainerState state = containerInfo.getState(); String logs = tailUtf8(postgres.getLogs(), MAX_DIAGNOSTIC_LOG_BYTES); + String internalSocketSelect1 = captureInternalSocketSelect1Diagnostics(postgres); return "PostgreSQL JDBC readiness timeout diagnostics:" + "\ncontainerId=" @@ -142,12 +144,45 @@ private static String capturePostgresReadinessDiagnostics(PostgreSQLContainer + (state == null ? null : state.getError()) + "\nmappedPortBindings[5432/tcp]=" + postgresPortBindings(containerInfo) + + "\n" + + internalSocketSelect1 + "\npostgresStartupLogTail(maxBytes=" + MAX_DIAGNOSTIC_LOG_BYTES + "):\n" + logs; } + private static String captureInternalSocketSelect1Diagnostics(PostgreSQLContainer postgres) { + try { + var result = + postgres.execInContainer( + "timeout", + "--signal=TERM", + "--kill-after=1s", + "5s", + "psql", + "--no-psqlrc", + "--host=/var/run/postgresql", + "--port=5432", + "--username=" + postgres.getUsername(), + "--dbname=" + postgres.getDatabaseName(), + "--tuples-only", + "--no-align", + "--command=SELECT 1"); + return "internalSocketSelect1.exitCode=" + + result.getExitCode() + + "\ninternalSocketSelect1.stdoutTail(maxBytes=512):\n" + + tailUtf8(result.getStdout(), 512) + + "\ninternalSocketSelect1.stderrTail(maxBytes=512):\n" + + tailUtf8(result.getStderr(), 512); + } catch (IOException | RuntimeException failure) { + return "internalSocketSelect1.diagnosticError=" + failure.getClass().getSimpleName(); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + return "internalSocketSelect1.diagnosticError=" + failure.getClass().getSimpleName(); + } + } + private static String resolvedHostAddresses(String host) { try { InetAddress[] addresses = InetAddress.getAllByName(host); From 54e9ef35454f669a1f07cec73d13511febe12233 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:30:07 +1300 Subject: [PATCH 34/36] Check mapped PostgreSQL readiness in manual Account fixtures --- .../AccountPostgresIntegrationFixture.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index aa45115401..432134d99f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -4,6 +4,7 @@ import java.util.Properties; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.springframework.aop.framework.ProxyFactory; import org.springframework.jdbc.core.JdbcTemplate; @@ -56,13 +57,14 @@ public void start() { "Docker is unavailable; the PostgreSQL test fixture requires Testcontainers"); container.start(); started = true; - if (requireDurablePrimary) { - try { + try { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(container); + if (requireDurablePrimary) { verifyDurablePrimary(); - } catch (RuntimeException unsuitable) { - stop(); - throw unsuitable; } + } catch (RuntimeException startupFailure) { + stop(); + throw startupFailure; } } From b76a748053b456033fa5ce6293bee59f05f140f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:28:32 +1300 Subject: [PATCH 35/36] docs: record container startup diagnostic limits --- design/project-management/ai-observations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e571574eba..70d3d56ae3 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -246,3 +246,8 @@ Entry format: - Context: On 2026-10-18 UTC / 2026-10-19 NZDT, Main prematurely resolved a routed #3269 H1 thread after the parent #3249 fix was published but before the child carry was published. The thread was immediately reopened and finally resolved after child commit `bc10` was published. - Observation: A routed parent fix alone did not prove that the child candidate carried the fix. - Expected pattern: Close a routed thread only against the relevant published candidate; verify the child carry publication before treating the thread as resolved. + +- `2026-10-20`: Preserve Testcontainers startup-failure limits + - Context: The focused canonical gate at `54e9ef35454f669a1f07cec73d13511febe12233` passed eight native cases across the two previously failing Account integration classes in 78.543 seconds, with zero failures, errors or skips; no Redis source or readiness change was made for this rerun. + - Observation: Testcontainers 2.0.5 `HostPortWaitStrategy` checks internal container and external mapped-port reachability concurrently, then reports a generic timeout without preserving the subcheck cause. Redis-ready logs alone do not isolate host forwarding. A child-command timeout or Future cancellation does not prove the Docker exec RPC ended. + - Expected pattern: Match exact container, fixture and mapped-port evidence before assigning a cause. Credit a focused rerun as its own proof; it neither erases the original failed aggregate nor proves a repair. From fd7b2b4a7af02bb87784bac0cc3cafda5bf54f15 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:22:07 +1300 Subject: [PATCH 36/36] test: await both selected-owner source PostgreSQL fixtures --- ...ectedOwnerSourceDisclosurePostgresIntegrationTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index 248b1df7cb..5aec4f2fc5 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -42,11 +42,13 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; 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.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -117,6 +119,12 @@ class SelectedOwnerSourceDisclosurePostgresIntegrationTest { "selected-disclosure-primary", "6379"); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(GDS); + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(ACCOUNT); + } + @TempDir Path temporary; @Test